Team Ai
Apppublic

MicroPanda123/RustBasic

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py90 linesDownload Raw Back to root
1"""2Sample from a trained model3"""4import os5import pickle6from contextlib import nullcontext7import torch8import tiktoken9from model import GPTConfig, GPT10import gradio as gr11 12# -----------------------------------------------------------------------------13init_from = 'resume' # either 'resume' (from an out_dir) or a gpt2 variant (e.g. 'gpt2-xl')14out_dir = 'out-rust' # ignored if init_from is not 'resume'15max_new_tokens = 500 # number of tokens generated in each sample16temperature = 0.8 # 1.0 = no change, < 1.0 = less random, > 1.0 = more random, in predictions17top_k = 200 # retain only the top_k most likely tokens, clamp others to have 0 probability18seed = 133719device = 'cpu' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1', etc.20dtype = 'bfloat16' if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else 'float16' # 'float32' or 'bfloat16' or 'float16'21compile = False # use PyTorch 2.0 to compile the model to be faster22# -----------------------------------------------------------------------------23 24torch.manual_seed(seed)25torch.cuda.manual_seed(seed)26torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul27torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn28device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast29ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]30ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)31 32# model33if init_from == 'resume':34    # init from a model saved in a specific directory35    ckpt_path = os.path.join(out_dir, 'ckpt.pt')36    checkpoint = torch.load(ckpt_path, map_location=device)37    gptconf = GPTConfig(**checkpoint['model_args'])38    model = GPT(gptconf)39    state_dict = checkpoint['model']40    unwanted_prefix = '_orig_mod.'41    for k,v in list(state_dict.items()):42        if k.startswith(unwanted_prefix):43            state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)44    model.load_state_dict(state_dict)45elif init_from.startswith('gpt2'):46    # init from a given GPT-2 model47    model = GPT.from_pretrained(init_from, dict(dropout=0.0))48 49model.eval()50model.to(device)51if compile:52    model = torch.compile(model) # requires PyTorch 2.0 (optional)53 54# look for the meta pickle in case it is available in the dataset folder55load_meta = False56if init_from == 'resume' and 'config' in checkpoint and 'dataset' in checkpoint['config']: # older checkpoints might not have these...57    meta_path = os.path.join('data', checkpoint['config']['dataset'], 'meta.pkl')58    load_meta = os.path.exists(meta_path)59if load_meta:60    print(f"Loading meta from {meta_path}...")61    with open(meta_path, 'rb') as f:62        meta = pickle.load(f)63    # TODO want to make this more general to arbitrary encoder/decoder schemes64    stoi, itos = meta['stoi'], meta['itos']65    encode = lambda s: [stoi[c] for c in s]66    decode = lambda l: ''.join([itos[i] for i in l])67else:68    # ok let's assume gpt-2 encodings by default69    print("No meta.pkl found, assuming GPT-2 encodings...")70    enc = tiktoken.get_encoding("gpt2")71    encode = lambda s: enc.encode(s, allowed_special={"<|endoftext|>"})72    decode = lambda l: enc.decode(l)73 74# encode the beginning of the prompt75 76def generator(start, tokens):77    tokens = int(tokens)78    start_ids = encode(start)79    x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])80 81    # run generation82    with torch.no_grad():83        with ctx:84            y = model.generate(x, tokens, temperature=temperature, top_k=top_k)85    return decode(y[0].tolist())86 87demo = gr.Interface(fn=generator, inputs=["text", "number"], outputs="text")88    89demo.launch()  90