Download run.py from Astra228/ChudGPT-Femboy: direct link, hf CLI and curl.
- Browser
- Download file 2.52 kB
-
https://huggingface.co/Astra228/ChudGPT-Femboy/resolve/main/run.py
- Command line
-
hf download hf://Astra228/ChudGPT-Femboy/run.py
-
curl -L -o run.py https://huggingface.co/Astra228/ChudGPT-Femboy/resolve/main/run.py
2.52 kB
| import argparse | |
| import json | |
| from pathlib import Path | |
| import torch | |
| from tokenizers import Tokenizer | |
| from safetensors.torch import load_file | |
| root = Path(__file__).resolve().parent | |
| p = argparse.ArgumentParser(description="Local neural inference; no external model API") | |
| p.add_argument('--message') | |
| p.add_argument('--device', choices=['cpu','cuda'], default='cpu') | |
| p.add_argument('--max-new-tokens', type=int, default=128) | |
| a = p.parse_args() | |
| torch.set_num_threads(2) | |
| cfg = json.loads((root/'config.json').read_text()) | |
| if not 1 <= a.max_new_tokens <= 256: | |
| p.error('max-new-tokens must be between 1 and 256') | |
| tok = Tokenizer.from_file(str(root/'tokenizer.json')) | |
| if cfg['kind'] == 'femboy': | |
| from model import Config, Model, generate | |
| from conversation import conversation_prompt | |
| model = Model(Config(**cfg['architecture'])) | |
| else: | |
| from chudlm.model import ModelConfig, TransformerLM | |
| from chudlm.generation import generate | |
| from chudlm.prompts import build_context_token_ids | |
| model = TransformerLM(ModelConfig(**cfg['architecture'])) | |
| model.load_state_dict(load_file(str(root/'model.safetensors')), strict=True) | |
| model.to(a.device).eval() | |
| messages = [] | |
| def reply(text): | |
| messages.append({'role':'user','content':text}) | |
| if cfg['kind'] == 'femboy': | |
| ids = conversation_prompt(tok, messages, model.config.context, a.max_new_tokens) | |
| output = generate(model, torch.tensor([ids],device=a.device), max_tokens=a.max_new_tokens, | |
| temperature=0, eos=tok.token_to_id('<eos>'), | |
| stop_ids=[[tok.token_to_id('<'+r+'>')] for r in ['user','system','assistant']], | |
| valid_vocab_size=tok.get_vocab_size()) | |
| else: | |
| _, ids = build_context_token_ids(tok,messages,model.config.context_length) | |
| output = generate(model,torch.tensor([ids],device=a.device),a.max_new_tokens, | |
| temperature=0,eos_token_id=tok.token_to_id('<eos>'))[0,len(ids):].tolist() | |
| result = tok.decode(output,skip_special_tokens=True).strip() | |
| messages.append({'role':'assistant','content':result}) | |
| return result | |
| if a.message is not None: | |
| print(reply(a.message)) | |
| else: | |
| print(cfg['name']+' - /quit to exit, /clear to reset local conversation') | |
| while True: | |
| try: text=input('You: ') | |
| except (EOFError,KeyboardInterrupt): break | |
| if text.strip()=='/quit': break | |
| if text.strip()=='/clear': messages.clear(); continue | |
| if text.strip(): print('Assistant: '+reply(text)) | |