1
0

prefix_cache_example.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from aphrodite import LLM, SamplingParams
  2. prefix = (
  3. "You are an expert school principal, skilled in effectively managing "
  4. "faculty and staff. Draft 10-15 questions for a potential first grade "
  5. "Head Teacher for my K-12, all-girls', independent school that emphasizes "
  6. "community, joyful discovery, and life-long learning. The candidate is "
  7. "coming in for a first-round panel interview for a 8th grade Math "
  8. "teaching role. They have 5 years of previous teaching experience "
  9. "as an assistant teacher at a co-ed, public school with experience "
  10. "in middle school math teaching. Based on these information, fulfill "
  11. "the following paragraph: ")
  12. # Sample prompts.
  13. prompts = [
  14. "Hello, my name is",
  15. "The president of the United States is",
  16. "The capital of France is",
  17. "The future of AI is",
  18. ]
  19. # Create a sampling params object.
  20. sampling_params = SamplingParams(temperature=0.0)
  21. # Create an LLM.
  22. llm = LLM(model="EleutherAI/pythia-70m-deduped")
  23. generating_prompts = [prefix + prompt for prompt in prompts]
  24. # Generate texts from the prompts. The output is a list of RequestOutput objects
  25. # that contain the prompt, generated text, and other information.
  26. outputs = llm.generate(generating_prompts, sampling_params)
  27. # Print the outputs.
  28. for output in outputs:
  29. prompt = output.prompt
  30. generated_text = output.outputs[0].text
  31. print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
  32. print("-" * 80)
  33. # -1 since the last token can change when concatenating prompts.
  34. prefix_pos = len(llm.llm_engine.tokenizer.encode(prefix)) - 1
  35. # The llm.generate call will batch all prompts and send the batch at once if resources allow.
  36. # The prefix will only be cached after the first batch is processed, so we need to call generate once
  37. # to calculate the prefix and cache it.
  38. outputs = llm.generate(generating_prompts[0],
  39. sampling_params,
  40. prefix_pos=[prefix_pos])
  41. # Subsequent batches can leverage the cached prefix
  42. outputs = llm.generate(generating_prompts,
  43. sampling_params,
  44. prefix_pos=[prefix_pos] * len(generating_prompts))
  45. # Print the outputs. You should see the same outputs as before
  46. for output in outputs:
  47. prompt = output.prompt
  48. generated_text = output.outputs[0].text
  49. print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")