Spaces:
Paused
Paused
import gradio as gr | |
from model import GPTConfig, GPT | |
import torch | |
def remove_caseifer(text): | |
new_text = "" | |
i = 0 | |
while i < len(text): | |
if text[i] == "^": | |
if i+1 < len(text): | |
new_text += text[i+1].upper() | |
i += 1 | |
else: | |
pass # skip this index | |
else: | |
new_text += text[i] | |
i += 1 | |
return new_text | |
def add_caseifer(text): | |
new_text = "" | |
for char in text: | |
if char.isupper(): | |
new_text += "^" + char.lower() | |
else: | |
new_text += char | |
return new_text | |
max_new_tokens = 175 # number of tokens generated in each sample | |
temperature = 0.8 # 1.0 = no change, < 1.0 = less random, > 1.0 = more random, in predictions | |
top_k = 200 # retain only the top_k most likely tokens, clamp others to have 0 probability | |
device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1', etc. | |
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul | |
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn | |
device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast | |
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype] | |
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype) | |
# init from a model saved in a specific directory | |
ckpt_path = os.path.join(out_dir, 'ckpt.pt') | |
checkpoint = torch.load(ckpt_path, map_location=device) | |
gptconf = GPTConfig(**checkpoint['model_args']) | |
model = GPT(gptconf) | |
state_dict = checkpoint['model'] | |
unwanted_prefix = '_orig_mod.' | |
for k,v in list(state_dict.items()): | |
if k.startswith(unwanted_prefix): | |
state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k) | |
model.load_state_dict(state_dict) | |
model.eval() | |
model.to(device) | |
meta_path = os.path.join(out_dir, 'meta.pkl') | |
load_meta = os.path.exists(meta_path) | |
with open(meta_path, 'rb') as f: | |
meta = pickle.load(f) | |
# TODO want to make this more general to arbitrary encoder/decoder schemes | |
stoi, itos = meta['stoi'], meta['itos'] | |
encode = lambda s: [stoi[c] for c in s] | |
decode = lambda l: ''.join([itos[i] for i in l]) | |
def gen(input): | |
start_ids = encode(add_caseifer(input)) | |
x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...]) | |
y = model.generate(x, max_new_tokens, temperature=temperature, top_k=top_k) | |
return remove_caseifer(decode(y[0].tolist())) | |
iface = gr.Interface(fn=gen, inputs="text", outputs="text") | |
iface.launch() |