inference.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. import fire
  4. from transformers import AutoTokenizer, AutoModelForCausalLM
  5. from llama_recipes.inference.prompt_format_utils import build_prompt, create_conversation, LLAMA_GUARD_CATEGORY
  6. from typing import List, Tuple
  7. from enum import Enum
  8. class AgentType(Enum):
  9. AGENT = "Agent"
  10. USER = "User"
  11. def main():
  12. """
  13. Entry point of the program for generating text using a pretrained model.
  14. Args:
  15. ckpt_dir (str): The directory containing checkpoint files for the pretrained model.
  16. tokenizer_path (str): The path to the tokenizer model used for text encoding/decoding.
  17. temperature (float, optional): The temperature value for controlling randomness in generation.
  18. Defaults to 0.6.
  19. top_p (float, optional): The top-p sampling parameter for controlling diversity in generation.
  20. Defaults to 0.9.
  21. max_seq_len (int, optional): The maximum sequence length for input prompts. Defaults to 128.
  22. max_gen_len (int, optional): The maximum length of generated sequences. Defaults to 64.
  23. max_batch_size (int, optional): The maximum batch size for generating sequences. Defaults to 4.
  24. """
  25. prompts: List[Tuple[List[str], AgentType]] = [
  26. (["<Sample user prompt>"], AgentType.USER),
  27. (["<Sample user prompt>",
  28. "<Sample agent response>"], AgentType.AGENT),
  29. (["<Sample user prompt>",
  30. "<Sample agent response>",
  31. "<Sample user reply>",
  32. "<Sample agent response>",], AgentType.AGENT),
  33. ]
  34. model_id = "meta-llama/LlamaGuard-7b"
  35. tokenizer = AutoTokenizer.from_pretrained(model_id)
  36. model = AutoModelForCausalLM.from_pretrained(model_id, load_in_8bit=True, device_map="auto")
  37. for prompt in prompts:
  38. formatted_prompt = build_prompt(
  39. prompt[1],
  40. LLAMA_GUARD_CATEGORY,
  41. create_conversation(prompt[0]))
  42. input = tokenizer([formatted_prompt], return_tensors="pt").to("cuda")
  43. prompt_len = input["input_ids"].shape[-1]
  44. output = model.generate(**input, max_new_tokens=100, pad_token_id=0)
  45. results = tokenizer.decode(output[0][prompt_len:], skip_special_tokens=True)
  46. print(prompt[0])
  47. print(f"> {results}")
  48. print("\n==================================\n")
  49. if __name__ == "__main__":
  50. fire.Fire(main)