inference.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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, BitsAndBytesConfig
  5. from llama_recipes.inference.prompt_format_utils import build_default_prompt, create_conversation, LlamaGuardVersion
  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. model_id: str = "meta-llama/LlamaGuard-7b",
  13. llama_guard_version: LlamaGuardVersion = LlamaGuardVersion.LLAMA_GUARD_1
  14. ):
  15. """
  16. Entry point for Llama Guard inference sample script.
  17. This function loads Llama Guard from Hugging Face or a local model and
  18. executes the predefined prompts in the script to showcase how to do inference with Llama Guard.
  19. Args:
  20. model_id (str): The ID of the pretrained model to use for generation. This can be either the path to a local folder containing the model files,
  21. or the repository ID of a model hosted on the Hugging Face Hub. Defaults to 'meta-llama/LlamaGuard-7b'.
  22. llama_guard_version (LlamaGuardVersion): The version of the Llama Guard model to use for formatting prompts. Defaults to LLAMA_GUARD_1.
  23. """
  24. try:
  25. llama_guard_version = LlamaGuardVersion[llama_guard_version]
  26. except KeyError as e:
  27. raise ValueError(f"Invalid Llama Guard version '{llama_guard_version}'. Valid values are: {', '.join([lgv.name for lgv in LlamaGuardVersion])}") from e
  28. prompts: List[Tuple[List[str], AgentType]] = [
  29. (["<Sample user prompt>"], AgentType.USER),
  30. (["<Sample user prompt>",
  31. "<Sample agent response>"], AgentType.AGENT),
  32. (["<Sample user prompt>",
  33. "<Sample agent response>",
  34. "<Sample user reply>",
  35. "<Sample agent response>",], AgentType.AGENT),
  36. ]
  37. quantization_config = BitsAndBytesConfig(load_in_8bit=True)
  38. tokenizer = AutoTokenizer.from_pretrained(model_id)
  39. model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config, device_map="auto")
  40. for prompt in prompts:
  41. formatted_prompt = build_default_prompt(
  42. prompt[1],
  43. create_conversation(prompt[0]),
  44. llama_guard_version)
  45. input = tokenizer([formatted_prompt], return_tensors="pt").to("cuda")
  46. prompt_len = input["input_ids"].shape[-1]
  47. output = model.generate(**input, max_new_tokens=100, pad_token_id=0)
  48. results = tokenizer.decode(output[0][prompt_len:], skip_special_tokens=True)
  49. print(prompt[0])
  50. print(f"> {results}")
  51. print("\n==================================\n")
  52. if __name__ == "__main__":
  53. try:
  54. fire.Fire(main)
  55. except Exception as e:
  56. print(e)