"""Локальный диалог с SalgrAI v2.1 Pro или Pro Coder в Transformers.""" import argparse import torch from transformers import AutoModelForCausalLM, AutoTokenizer def fit_history(tokenizer, messages, budget): """Сохранить последние полные пары, помещающиеся в контекст.""" history = messages while history: inputs = tokenizer.apply_chat_template( history, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ) if inputs["input_ids"].shape[1] <= budget: return history, inputs history = history[2:] raise ValueError("Последнее сообщение превышает лимит контекста.") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("model", nargs="?", default=".", help="Папка или репозиторий модели") parser.add_argument("--context", type=int, default=4096, help="Лимит токенов вместе с ответом") args = parser.parse_args() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") dtype = torch.bfloat16 if device.type == "cuda" and torch.cuda.is_bf16_supported() else torch.float32 tokenizer = AutoTokenizer.from_pretrained(args.model) model = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype).to(device).eval() max_new = model.generation_config.max_new_tokens if not max_new or not max_new < args.context <= model.config.max_position_embeddings: parser.error("--context должен вмещать ответ и укладываться в лимит модели") history = [] while True: try: text = input("вы> ").strip() except (EOFError, KeyboardInterrupt): break if text == "/exit": break if text == "/reset": history = [] continue if not text: continue pending = history + [{"role": "user", "content": text}] try: history, inputs = fit_history(tokenizer, pending, args.context - max_new) except ValueError as exc: print(exc) continue inputs = inputs.to(device) with torch.inference_mode(): output = model.generate(**inputs) answer = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip() history.append({"role": "assistant", "content": answer}) print("SalgrAI>", answer) if __name__ == "__main__": main()