MicroPanda123 commited on
Commit
a226856
·
1 Parent(s): dc752d8

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -89
app.py DELETED
@@ -1,89 +0,0 @@
1
- """
2
- Sample from a trained model
3
- """
4
- import os
5
- import pickle
6
- from contextlib import nullcontext
7
- import torch
8
- import tiktoken
9
- from model import GPTConfig, GPT
10
- import gradio as gr
11
-
12
- # -----------------------------------------------------------------------------
13
- init_from = 'resume' # either 'resume' (from an out_dir) or a gpt2 variant (e.g. 'gpt2-xl')
14
- out_dir = 'out-python' # ignored if init_from is not 'resume'
15
- max_new_tokens = 500 # number of tokens generated in each sample
16
- temperature = 0.8 # 1.0 = no change, < 1.0 = less random, > 1.0 = more random, in predictions
17
- top_k = 200 # retain only the top_k most likely tokens, clamp others to have 0 probability
18
- seed = 1337
19
- device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1', etc.
20
- dtype = 'bfloat16' if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else 'float16' # 'float32' or 'bfloat16' or 'float16'
21
- compile = False # use PyTorch 2.0 to compile the model to be faster
22
- # -----------------------------------------------------------------------------
23
-
24
- torch.manual_seed(seed)
25
- torch.cuda.manual_seed(seed)
26
- torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
27
- torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
28
- device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
29
- ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
30
- ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
31
-
32
- # model
33
- if init_from == 'resume':
34
- # init from a model saved in a specific directory
35
- 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)
45
- elif init_from.startswith('gpt2'):
46
- # init from a given GPT-2 model
47
- model = GPT.from_pretrained(init_from, dict(dropout=0.0))
48
-
49
- model.eval()
50
- model.to(device)
51
- if 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 folder
55
- load_meta = False
56
- if 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)
59
- if 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 schemes
64
- 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])
67
- else:
68
- # ok let's assume gpt-2 encodings by default
69
- 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 prompt
75
-
76
- def 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 generation
82
- 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
-
87
- demo = gr.Interface(fn=generator, inputs=["text", "number"], outputs="text")
88
-
89
- demo.launch(share=True)