chat.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. # Copyright 2025 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import asyncio
  15. import copy
  16. import json
  17. import os
  18. import platform
  19. import re
  20. import string
  21. import time
  22. from argparse import ArgumentParser, Namespace
  23. from collections.abc import AsyncIterator
  24. from dataclasses import dataclass, field
  25. from threading import Thread
  26. from typing import Optional
  27. import yaml
  28. from huggingface_hub import AsyncInferenceClient, ChatCompletionStreamOutput
  29. from transformers import (
  30. AutoTokenizer,
  31. GenerationConfig,
  32. PreTrainedTokenizer,
  33. )
  34. from transformers.commands import BaseTransformersCLICommand
  35. from transformers.commands.serving import ServeArguments, ServeCommand
  36. from transformers.utils import is_rich_available, is_torch_available
  37. try:
  38. import readline # noqa importing this enables GNU readline capabilities
  39. except ImportError:
  40. # some platforms may not support readline: https://docs.python.org/3/library/readline.html
  41. pass
  42. if platform.system() != "Windows":
  43. import pwd
  44. if is_rich_available():
  45. from rich.console import Console
  46. from rich.live import Live
  47. from rich.markdown import Markdown
  48. if is_torch_available():
  49. import torch
  50. from transformers import (
  51. AutoModelForCausalLM,
  52. BitsAndBytesConfig,
  53. )
  54. ALLOWED_KEY_CHARS = set(string.ascii_letters + string.whitespace)
  55. ALLOWED_VALUE_CHARS = set(
  56. string.ascii_letters + string.digits + string.whitespace + r".!\"#$%&'()*+,\-/:<=>?@[]^_`{|}~"
  57. )
  58. DEFAULT_EXAMPLES = {
  59. "llama": {"text": "There is a Llama in my lawn, how can I get rid of it?"},
  60. "code": {
  61. "text": (
  62. "Write a Python function that integrates any Python function f(x) numerically over an arbitrary "
  63. "interval [x_start, x_end]."
  64. ),
  65. },
  66. "helicopter": {"text": "How many helicopters can a human eat in one sitting?"},
  67. "numbers": {"text": "Count to 10 but skip every number ending with an 'e'"},
  68. "birds": {"text": "Why aren't birds real?"},
  69. "socks": {"text": "Why is it important to eat socks after meditating?"},
  70. "numbers2": {"text": "Which number is larger, 9.9 or 9.11?"},
  71. }
  72. # Printed at the start of a chat session
  73. HELP_STRING_MINIMAL = """
  74. **TRANSFORMERS CHAT INTERFACE**
  75. Chat interface to try out a model. Besides chatting with the model, here are some basic commands:
  76. - **!help**: shows all available commands (set generation settings, save chat, etc.)
  77. - **!status**: shows the current status of the model and generation settings
  78. - **!clear**: clears the current conversation and starts a new one
  79. - **!exit**: closes the interface
  80. """
  81. # Printed when the user types `help` in the chat session
  82. HELP_STRING = f"""
  83. **TRANSFORMERS CHAT INTERFACE HELP**
  84. Full command list:
  85. - **!help**: shows this help message
  86. - **!clear**: clears the current conversation and starts a new one
  87. - **!status**: shows the current status of the model and generation settings
  88. - **!example {{NAME}}**: loads example named `{{NAME}}` from the config and uses it as the user input.
  89. Available example names: `{"`, `".join(DEFAULT_EXAMPLES.keys())}`
  90. - **!set {{ARG_1}}={{VALUE_1}} {{ARG_2}}={{VALUE_2}}** ...: changes the system prompt or generation settings (multiple
  91. settings are separated by a space). Accepts the same flags and format as the `generate_flags` CLI argument.
  92. If you're a new user, check this basic flag guide: https://huggingface.co/docs/transformers/llm_tutorial#common-options
  93. - **!save {{SAVE_NAME}} (optional)**: saves the current chat and settings to file by default to
  94. `./chat_history/{{MODEL_NAME}}/chat_{{DATETIME}}.yaml` or `{{SAVE_NAME}}` if provided
  95. - **!exit**: closes the interface
  96. """
  97. class RichInterface:
  98. def __init__(self, model_name: Optional[str] = None, user_name: Optional[str] = None):
  99. self._console = Console()
  100. if model_name is None:
  101. self.model_name = "assistant"
  102. else:
  103. self.model_name = model_name
  104. if user_name is None:
  105. self.user_name = "user"
  106. else:
  107. self.user_name = user_name
  108. async def stream_output(self, stream: AsyncIterator[ChatCompletionStreamOutput]) -> tuple[str, int]:
  109. self._console.print(f"[bold blue]<{self.model_name}>:")
  110. with Live(console=self._console, refresh_per_second=4) as live:
  111. text = ""
  112. async for token in await stream:
  113. outputs = token.choices[0].delta.content
  114. if not outputs:
  115. continue
  116. # Escapes single words encased in <>, e.g. <think> -> \<think\>, for proper rendering in Markdown.
  117. # It only escapes single words that may have `_`, optionally following a `/` (e.g. </think>)
  118. outputs = re.sub(r"<(/*)(\w*)>", r"\<\1\2\>", outputs)
  119. text += outputs
  120. # Render the accumulated text as Markdown
  121. # NOTE: this is a workaround for the rendering "unstandard markdown"
  122. # in rich. The chatbots output treat "\n" as a new line for
  123. # better compatibility with real-world text. However, rendering
  124. # in markdown would break the format. It is because standard markdown
  125. # treat a single "\n" in normal text as a space.
  126. # Our workaround is adding two spaces at the end of each line.
  127. # This is not a perfect solution, as it would
  128. # introduce trailing spaces (only) in code block, but it works well
  129. # especially for console output, because in general the console does not
  130. # care about trailing spaces.
  131. lines = []
  132. for line in text.splitlines():
  133. lines.append(line)
  134. if line.startswith("```"):
  135. # Code block marker - do not add trailing spaces, as it would
  136. # break the syntax highlighting
  137. lines.append("\n")
  138. else:
  139. lines.append(" \n")
  140. markdown = Markdown("".join(lines).strip(), code_theme="github-dark")
  141. # Update the Live console output
  142. live.update(markdown, refresh=True)
  143. self._console.print()
  144. return text
  145. def input(self) -> str:
  146. """Gets user input from the console."""
  147. input = self._console.input(f"[bold red]<{self.user_name}>:\n")
  148. self._console.print()
  149. return input
  150. def clear(self):
  151. """Clears the console."""
  152. self._console.clear()
  153. def print_user_message(self, text: str):
  154. """Prints a user message to the console."""
  155. self._console.print(f"[bold red]<{self.user_name}>:[/ bold red]\n{text}")
  156. self._console.print()
  157. def print_color(self, text: str, color: str):
  158. """Prints text in a given color to the console."""
  159. self._console.print(f"[bold {color}]{text}")
  160. self._console.print()
  161. def print_help(self, minimal: bool = False):
  162. """Prints the help message to the console."""
  163. self._console.print(Markdown(HELP_STRING_MINIMAL if minimal else HELP_STRING))
  164. self._console.print()
  165. def print_status(self, model_name: str, generation_config: GenerationConfig, model_kwargs: dict):
  166. """Prints the status of the model and generation settings to the console."""
  167. self._console.print(f"[bold blue]Model: {model_name}\n")
  168. if model_kwargs:
  169. self._console.print(f"[bold blue]Model kwargs: {model_kwargs}")
  170. self._console.print(f"[bold blue]{generation_config}")
  171. self._console.print()
  172. @dataclass
  173. class ChatArguments:
  174. r"""
  175. Arguments for the chat CLI.
  176. See the metadata arg for each argument's description -- the medatata will be printed with
  177. `transformers chat --help`
  178. """
  179. # General settings
  180. model_name_or_path: Optional[str] = field(
  181. default=None,
  182. metadata={
  183. "help": "Name of the pre-trained model. The positional argument will take precedence if both are passed."
  184. },
  185. )
  186. user: Optional[str] = field(
  187. default=None,
  188. metadata={"help": "Username to display in chat interface. Defaults to the current user's name."},
  189. )
  190. system_prompt: Optional[str] = field(default=None, metadata={"help": "System prompt."})
  191. save_folder: str = field(default="./chat_history/", metadata={"help": "Folder to save chat history."})
  192. examples_path: Optional[str] = field(default=None, metadata={"help": "Path to a yaml file with examples."})
  193. verbose: bool = field(default=False, metadata={"help": "Whether to show runtime warnings in the chat interface."})
  194. # Generation settings
  195. generation_config: Optional[str] = field(
  196. default=None,
  197. metadata={
  198. "help": (
  199. "Path to a local generation config file or to a HuggingFace repo containing a "
  200. "`generation_config.json` file. Other generation settings passed as CLI arguments will be applied on "
  201. "top of this generation config."
  202. ),
  203. },
  204. )
  205. # Model loading
  206. model_revision: str = field(
  207. default="main",
  208. metadata={"help": "Specific model version to use (can be a branch name, tag name or commit id)."},
  209. )
  210. device: str = field(default="auto", metadata={"help": "Device to use for inference."})
  211. torch_dtype: Optional[str] = field(
  212. default=None,
  213. metadata={
  214. "help": "`torch_dtype` is deprecated! Please use `dtype` argument instead.",
  215. "choices": ["auto", "bfloat16", "float16", "float32"],
  216. },
  217. )
  218. dtype: Optional[str] = field(
  219. default="auto",
  220. metadata={
  221. "help": "Override the default `torch.dtype` and load the model under this dtype. If `'auto'` is passed, "
  222. "the dtype will be automatically derived from the model's weights.",
  223. "choices": ["auto", "bfloat16", "float16", "float32"],
  224. },
  225. )
  226. trust_remote_code: bool = field(
  227. default=False, metadata={"help": "Whether to trust remote code when loading a model."}
  228. )
  229. attn_implementation: Optional[str] = field(
  230. default=None,
  231. metadata={
  232. "help": "Which attention implementation to use; you can run --attn_implementation=flash_attention_2, in "
  233. "which case you must install this manually by running `pip install flash-attn --no-build-isolation`."
  234. },
  235. )
  236. load_in_8bit: bool = field(
  237. default=False,
  238. metadata={"help": "Whether to use 8 bit precision for the base model - works only with LoRA."},
  239. )
  240. load_in_4bit: bool = field(
  241. default=False,
  242. metadata={"help": "Whether to use 4 bit precision for the base model - works only with LoRA."},
  243. )
  244. bnb_4bit_quant_type: str = field(default="nf4", metadata={"help": "Quantization type.", "choices": ["fp4", "nf4"]})
  245. use_bnb_nested_quant: bool = field(default=False, metadata={"help": "Whether to use nested quantization."})
  246. # Serving settings
  247. host: str = field(default="localhost", metadata={"help": "Interface the server will listen to.."})
  248. port: int = field(default=8000, metadata={"help": "Port the server will listen to."})
  249. def __post_init__(self):
  250. """Only used for BC `torch_dtype` argument."""
  251. # In this case only the BC torch_dtype was given
  252. if self.torch_dtype is not None:
  253. if self.dtype is None:
  254. self.dtype = self.torch_dtype
  255. elif self.torch_dtype != self.dtype:
  256. raise ValueError(
  257. f"`torch_dtype` {self.torch_dtype} and `dtype` {self.dtype} have different values. `torch_dtype` is deprecated and "
  258. "will be removed in 4.59.0, please set `dtype` instead."
  259. )
  260. def chat_command_factory(args: Namespace):
  261. """
  262. Factory function used to chat with a local model.
  263. """
  264. return ChatCommand(args)
  265. class ChatCommand(BaseTransformersCLICommand):
  266. @staticmethod
  267. def register_subcommand(parser: ArgumentParser):
  268. """
  269. Register this command to argparse so it's available for the transformer-cli
  270. Args:
  271. parser: Root parser to register command-specific arguments
  272. """
  273. dataclass_types = (ChatArguments,)
  274. chat_parser = parser.add_parser("chat", dataclass_types=dataclass_types)
  275. group = chat_parser.add_argument_group("Positional arguments")
  276. group.add_argument(
  277. "model_name_or_path_or_address",
  278. type=str,
  279. default=None,
  280. help="Name of the pre-trained model or address to connect to.",
  281. )
  282. group.add_argument(
  283. "generate_flags",
  284. type=str,
  285. default=None,
  286. help=(
  287. "Flags to pass to `generate`, using a space as a separator between flags. Accepts booleans, numbers, "
  288. "and lists of integers, more advanced parameterization should be set through --generation-config. "
  289. "Example: `transformers chat <model_repo> max_new_tokens=100 do_sample=False eos_token_id=[1,2]`. "
  290. "If you're a new user, check this basic flag guide: "
  291. "https://huggingface.co/docs/transformers/llm_tutorial#common-options"
  292. ),
  293. nargs="*",
  294. )
  295. chat_parser.set_defaults(func=chat_command_factory)
  296. def __init__(self, args):
  297. if args.model_name_or_path_or_address is not None:
  298. name = args.model_name_or_path_or_address
  299. if name.startswith("http") or name.startswith("https") or name.startswith("localhost"):
  300. self.spawn_backend = False
  301. if args.host != "localhost" or args.port != 8000:
  302. raise ValueError(
  303. "Looks like you’ve set both a server address and a custom host/port. "
  304. "Please pick just one way to specify the server."
  305. )
  306. args.host, args.port = args.model_name_or_path_or_address.rsplit(":", 1)
  307. if args.model_name_or_path is None:
  308. raise ValueError(
  309. "When connecting to a server, please specify a model name with the --model_name_or_path flag."
  310. )
  311. else:
  312. self.spawn_backend = True
  313. args.model_name_or_path = args.model_name_or_path_or_address
  314. if not is_rich_available() and (not is_torch_available() and self.spawn_backend):
  315. raise ImportError(
  316. "You need to install rich to use the chat interface. Additionally, you have not specified a remote "
  317. "endpoint and are therefore spawning a backend. Torch is required for this: (`pip install rich torch`)"
  318. )
  319. elif not is_rich_available():
  320. raise ImportError("You need to install rich to use the chat interface. (`pip install rich`)")
  321. elif not is_torch_available() and self.spawn_backend:
  322. raise ImportError(
  323. "You have not specified a remote endpoint and are therefore spawning a backend. Torch is required "
  324. "for this: (`pip install rich torch`)"
  325. )
  326. self.args = args
  327. # -----------------------------------------------------------------------------------------------------------------
  328. # Chat session methods
  329. @staticmethod
  330. def get_username() -> str:
  331. """Returns the username of the current user."""
  332. if platform.system() == "Windows":
  333. return os.getlogin()
  334. else:
  335. return pwd.getpwuid(os.getuid()).pw_name
  336. @staticmethod
  337. def save_chat(chat, args: ChatArguments, filename: Optional[str] = None) -> str:
  338. """Saves the chat history to a file."""
  339. output_dict = {}
  340. output_dict["settings"] = vars(args)
  341. output_dict["chat_history"] = chat
  342. folder = args.save_folder
  343. if filename is None:
  344. time_str = time.strftime("%Y-%m-%d_%H-%M-%S")
  345. filename = f"{args.model_name_or_path_or_address}/chat_{time_str}.json"
  346. filename = os.path.join(folder, filename)
  347. os.makedirs(os.path.dirname(filename), exist_ok=True)
  348. with open(filename, "w") as f:
  349. json.dump(output_dict, f, indent=4)
  350. return os.path.abspath(filename)
  351. @staticmethod
  352. def clear_chat_history(system_prompt: Optional[str] = None) -> list[dict]:
  353. """Clears the chat history."""
  354. if system_prompt is None:
  355. chat = []
  356. else:
  357. chat = [{"role": "system", "content": system_prompt}]
  358. return chat
  359. # -----------------------------------------------------------------------------------------------------------------
  360. # Input parsing methods
  361. def parse_generate_flags(self, generate_flags: list[str]) -> dict:
  362. """Parses the generate flags from the user input into a dictionary of `generate` kwargs."""
  363. if len(generate_flags) == 0:
  364. return {}
  365. # Assumption: `generate_flags` is a list of strings, each string being a `flag=value` pair, that can be parsed
  366. # into a json string if we:
  367. # 1. Add quotes around each flag name
  368. generate_flags_as_dict = {'"' + flag.split("=")[0] + '"': flag.split("=")[1] for flag in generate_flags}
  369. # 2. Handle types:
  370. # 2. a. booleans should be lowercase, None should be null
  371. generate_flags_as_dict = {
  372. k: v.lower() if v.lower() in ["true", "false"] else v for k, v in generate_flags_as_dict.items()
  373. }
  374. generate_flags_as_dict = {k: "null" if v == "None" else v for k, v in generate_flags_as_dict.items()}
  375. # 2. b. strings should be quoted
  376. def is_number(s: str) -> bool:
  377. # handle negative numbers
  378. s = s.removeprefix("-")
  379. return s.replace(".", "", 1).isdigit()
  380. generate_flags_as_dict = {k: f'"{v}"' if not is_number(v) else v for k, v in generate_flags_as_dict.items()}
  381. # 2. c. [no processing needed] lists are lists of ints because `generate` doesn't take lists of strings :)
  382. # We also mention in the help message that we only accept lists of ints for now.
  383. # 3. Join the result into a comma separated string
  384. generate_flags_string = ", ".join([f"{k}: {v}" for k, v in generate_flags_as_dict.items()])
  385. # 4. Add the opening/closing brackets
  386. generate_flags_string = "{" + generate_flags_string + "}"
  387. # 5. Remove quotes around boolean/null and around lists
  388. generate_flags_string = generate_flags_string.replace('"null"', "null")
  389. generate_flags_string = generate_flags_string.replace('"true"', "true")
  390. generate_flags_string = generate_flags_string.replace('"false"', "false")
  391. generate_flags_string = generate_flags_string.replace('"[', "[")
  392. generate_flags_string = generate_flags_string.replace(']"', "]")
  393. # 6. Replace the `=` with `:`
  394. generate_flags_string = generate_flags_string.replace("=", ":")
  395. try:
  396. processed_generate_flags = json.loads(generate_flags_string)
  397. except json.JSONDecodeError:
  398. raise ValueError(
  399. "Failed to convert `generate_flags` into a valid JSON object."
  400. "\n`generate_flags` = {generate_flags}"
  401. "\nConverted JSON string = {generate_flags_string}"
  402. )
  403. return processed_generate_flags
  404. def get_generation_parameterization(
  405. self, args: ChatArguments, model_generation_config: GenerationConfig
  406. ) -> tuple[GenerationConfig, dict]:
  407. """
  408. Returns a GenerationConfig object holding the generation parameters for the CLI command.
  409. """
  410. # No generation config arg provided -> use model's default generation config, then apply CLI defaults
  411. if args.generation_config is not None:
  412. if ".json" in args.generation_config: # is a local file
  413. dirname = os.path.dirname(args.generation_config)
  414. filename = os.path.basename(args.generation_config)
  415. generation_config = GenerationConfig.from_pretrained(dirname, filename)
  416. else:
  417. generation_config = GenerationConfig.from_pretrained(args.generation_config)
  418. else:
  419. # !!!!!!!!!
  420. # This is a chat session, so we have a few non-standard defaults
  421. # !!!!!!!!!
  422. generation_config = copy.deepcopy(model_generation_config)
  423. generation_config.update(**{"do_sample": True, "max_new_tokens": 256})
  424. # Finally: parse and apply `generate_flags`
  425. parsed_generate_flags = self.parse_generate_flags(args.generate_flags)
  426. model_kwargs = generation_config.update(**parsed_generate_flags)
  427. # `model_kwargs` contain non-generation flags in `parsed_generate_flags` that should be passed directly to
  428. # `generate`
  429. return generation_config, model_kwargs
  430. @staticmethod
  431. def parse_eos_tokens(
  432. tokenizer: PreTrainedTokenizer,
  433. generation_config: GenerationConfig,
  434. eos_tokens: Optional[str],
  435. eos_token_ids: Optional[str],
  436. ) -> tuple[int, list[int]]:
  437. """Retrieves the pad token ID and all possible EOS token IDs."""
  438. if generation_config.pad_token_id is None:
  439. pad_token_id = generation_config.eos_token_id
  440. else:
  441. pad_token_id = generation_config.pad_token_id
  442. all_eos_token_ids = []
  443. if eos_tokens is not None:
  444. all_eos_token_ids.extend(tokenizer.convert_tokens_to_ids(eos_tokens.split(",")))
  445. if eos_token_ids is not None:
  446. all_eos_token_ids.extend([int(token_id) for token_id in eos_token_ids.split(",")])
  447. if len(all_eos_token_ids) == 0:
  448. all_eos_token_ids.append(generation_config.eos_token_id)
  449. return pad_token_id, all_eos_token_ids
  450. # -----------------------------------------------------------------------------------------------------------------
  451. # Model loading and performance automation methods
  452. @staticmethod
  453. def get_quantization_config(model_args: ChatArguments) -> Optional[BitsAndBytesConfig]:
  454. if model_args.load_in_4bit:
  455. quantization_config = BitsAndBytesConfig(
  456. load_in_4bit=True,
  457. # For consistency with model weights, we use the same value as `dtype`
  458. bnb_4bit_compute_dtype=model_args.dtype,
  459. bnb_4bit_quant_type=model_args.bnb_4bit_quant_type,
  460. bnb_4bit_use_double_quant=model_args.use_bnb_nested_quant,
  461. bnb_4bit_quant_storage=model_args.dtype,
  462. )
  463. elif model_args.load_in_8bit:
  464. quantization_config = BitsAndBytesConfig(
  465. load_in_8bit=True,
  466. )
  467. else:
  468. quantization_config = None
  469. return quantization_config
  470. def load_model_and_tokenizer(self, args: ChatArguments) -> tuple["AutoModelForCausalLM", AutoTokenizer]:
  471. tokenizer = AutoTokenizer.from_pretrained(
  472. args.model_name_or_path_positional,
  473. revision=args.model_revision,
  474. trust_remote_code=args.trust_remote_code,
  475. )
  476. dtype = args.dtype if args.dtype in ["auto", None] else getattr(torch, args.dtype)
  477. quantization_config = self.get_quantization_config(args)
  478. model_kwargs = {
  479. "revision": args.model_revision,
  480. "attn_implementation": args.attn_implementation,
  481. "dtype": dtype,
  482. "device_map": "auto",
  483. "quantization_config": quantization_config,
  484. }
  485. model = AutoModelForCausalLM.from_pretrained(
  486. args.model_name_or_path_positional, trust_remote_code=args.trust_remote_code, **model_kwargs
  487. )
  488. if getattr(model, "hf_device_map", None) is None:
  489. model = model.to(args.device)
  490. return model, tokenizer
  491. # -----------------------------------------------------------------------------------------------------------------
  492. # User commands
  493. def handle_non_exit_user_commands(
  494. self,
  495. user_input: str,
  496. args: ChatArguments,
  497. interface: RichInterface,
  498. examples: dict[str, dict[str, str]],
  499. generation_config: GenerationConfig,
  500. model_kwargs: dict,
  501. chat: list[dict],
  502. ) -> tuple[list[dict], GenerationConfig, dict]:
  503. """
  504. Handles all user commands except for `!exit`. May update the chat history (e.g. reset it) or the
  505. generation config (e.g. set a new flag).
  506. """
  507. valid_command = True
  508. if user_input == "!clear":
  509. chat = self.clear_chat_history(args.system_prompt)
  510. interface.clear()
  511. elif user_input == "!help":
  512. interface.print_help()
  513. elif user_input.startswith("!save") and len(user_input.split()) < 2:
  514. split_input = user_input.split()
  515. if len(split_input) == 2:
  516. filename = split_input[1]
  517. else:
  518. filename = None
  519. filename = self.save_chat(chat, args, filename)
  520. interface.print_color(text=f"Chat saved in {filename}!", color="green")
  521. elif user_input.startswith("!set"):
  522. # splits the new args into a list of strings, each string being a `flag=value` pair (same format as
  523. # `generate_flags`)
  524. new_generate_flags = user_input[4:].strip()
  525. new_generate_flags = new_generate_flags.split()
  526. # sanity check: each member in the list must have an =
  527. for flag in new_generate_flags:
  528. if "=" not in flag:
  529. interface.print_color(
  530. text=(
  531. f"Invalid flag format, missing `=` after `{flag}`. Please use the format "
  532. "`arg_1=value_1 arg_2=value_2 ...`."
  533. ),
  534. color="red",
  535. )
  536. break
  537. else:
  538. # parses the new args into a dictionary of `generate` kwargs, and updates the corresponding variables
  539. parsed_new_generate_flags = self.parse_generate_flags(new_generate_flags)
  540. new_model_kwargs = generation_config.update(**parsed_new_generate_flags)
  541. model_kwargs.update(**new_model_kwargs)
  542. elif user_input.startswith("!example") and len(user_input.split()) == 2:
  543. example_name = user_input.split()[1]
  544. if example_name in examples:
  545. interface.clear()
  546. chat = []
  547. interface.print_user_message(examples[example_name]["text"])
  548. chat.append({"role": "user", "content": examples[example_name]["text"]})
  549. else:
  550. example_error = (
  551. f"Example {example_name} not found in list of available examples: {list(examples.keys())}."
  552. )
  553. interface.print_color(text=example_error, color="red")
  554. elif user_input == "!status":
  555. interface.print_status(
  556. model_name=args.model_name_or_path,
  557. generation_config=generation_config,
  558. model_kwargs=model_kwargs,
  559. )
  560. else:
  561. valid_command = False
  562. interface.print_color(text=f"'{user_input}' is not a valid command. Showing help message.", color="red")
  563. interface.print_help()
  564. return chat, valid_command, generation_config, model_kwargs
  565. # -----------------------------------------------------------------------------------------------------------------
  566. # Main logic
  567. def run(self):
  568. asyncio.run(self._inner_run())
  569. async def _inner_run(self):
  570. if self.spawn_backend:
  571. serve_args = ServeArguments(
  572. device=self.args.device,
  573. dtype=self.args.dtype,
  574. trust_remote_code=self.args.trust_remote_code,
  575. attn_implementation=self.args.attn_implementation,
  576. load_in_8bit=self.args.load_in_8bit,
  577. load_in_4bit=self.args.load_in_4bit,
  578. bnb_4bit_quant_type=self.args.bnb_4bit_quant_type,
  579. use_bnb_nested_quant=self.args.use_bnb_nested_quant,
  580. host=self.args.host,
  581. port=self.args.port,
  582. log_level="error",
  583. )
  584. serve_command = ServeCommand(serve_args)
  585. thread = Thread(target=serve_command.run)
  586. thread.daemon = True
  587. thread.start()
  588. model = self.args.model_name_or_path + "@" + self.args.model_revision
  589. host = "http://localhost" if self.args.host == "localhost" else self.args.host
  590. args = self.args
  591. if args.examples_path is None:
  592. examples = DEFAULT_EXAMPLES
  593. else:
  594. with open(args.examples_path) as f:
  595. examples = yaml.safe_load(f)
  596. if args.user is None:
  597. user = self.get_username()
  598. else:
  599. user = args.user
  600. model_generation_config = GenerationConfig.from_pretrained(args.model_name_or_path)
  601. generation_config, model_kwargs = self.get_generation_parameterization(args, model_generation_config)
  602. interface = RichInterface(model_name=args.model_name_or_path, user_name=user)
  603. interface.clear()
  604. chat = self.clear_chat_history(args.system_prompt)
  605. # Starts the session with a minimal help message at the top, so that a user doesn't get stuck
  606. interface.print_help(minimal=True)
  607. async with AsyncInferenceClient(f"{host}:{self.args.port}") as client:
  608. while True:
  609. try:
  610. user_input = interface.input()
  611. # User commands
  612. if user_input.startswith("!"):
  613. # `!exit` is special, it breaks the loop
  614. if user_input == "!exit":
  615. break
  616. else:
  617. chat, valid_command, generation_config, model_kwargs = self.handle_non_exit_user_commands(
  618. user_input=user_input,
  619. args=args,
  620. interface=interface,
  621. examples=examples,
  622. generation_config=generation_config,
  623. model_kwargs=model_kwargs,
  624. chat=chat,
  625. )
  626. # `!example` sends a user message to the model
  627. if not valid_command or not user_input.startswith("!example"):
  628. continue
  629. else:
  630. chat.append({"role": "user", "content": user_input})
  631. stream = client.chat_completion(
  632. chat,
  633. stream=True,
  634. extra_body={
  635. "generation_config": generation_config.to_json_string(),
  636. "model": model,
  637. },
  638. )
  639. model_output = await interface.stream_output(stream)
  640. chat.append({"role": "assistant", "content": model_output})
  641. except KeyboardInterrupt:
  642. break
  643. if __name__ == "__main__":
  644. args = ChatArguments()
  645. args.model_name_or_path_or_address = "meta-llama/Llama-3.2-3b-Instruct"
  646. args.model_name_or_path_or_address = "http://localhost:8000"
  647. chat = ChatCommand(args)
  648. chat.run()