Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

sample.py 3.8 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
  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. # -----------------------------------------------------------------------------
  11. init_from = 'resume' # either 'resume' (from an out_dir) or a gpt2 variant (e.g. 'gpt2-xl')
  12. out_dir = 'out' # ignored if init_from is not 'resume'
  13. start = "\n" # or "<|endoftext|>" or etc. Can also specify a file, use as: "FILE:prompt.txt"
  14. num_samples = 10 # number of samples to draw
  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. exec(open('configurator.py').read()) # overrides from command line or config file
  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. # model
  32. if init_from == 'resume':
  33. # init from a model saved in a specific directory
  34. ckpt_path = os.path.join(out_dir, 'ckpt.pt')
  35. checkpoint = torch.load(ckpt_path, map_location=device)
  36. gptconf = GPTConfig(**checkpoint['model_args'])
  37. model = GPT(gptconf)
  38. state_dict = checkpoint['model']
  39. unwanted_prefix = '_orig_mod.'
  40. for k,v in list(state_dict.items()):
  41. if k.startswith(unwanted_prefix):
  42. state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
  43. model.load_state_dict(state_dict)
  44. elif init_from.startswith('gpt2'):
  45. # init from a given GPT-2 model
  46. model = GPT.from_pretrained(init_from, dict(dropout=0.0))
  47. model.eval()
  48. model.to(device)
  49. if compile:
  50. model = torch.compile(model) # requires PyTorch 2.0 (optional)
  51. # look for the meta pickle in case it is available in the dataset folder
  52. load_meta = False
  53. if init_from == 'resume' and 'config' in checkpoint and 'dataset' in checkpoint['config']: # older checkpoints might not have these...
  54. meta_path = os.path.join('data', checkpoint['config']['dataset'], 'meta.pkl')
  55. load_meta = os.path.exists(meta_path)
  56. if load_meta:
  57. print(f"Loading meta from {meta_path}...")
  58. with open(meta_path, 'rb') as f:
  59. meta = pickle.load(f)
  60. # TODO want to make this more general to arbitrary encoder/decoder schemes
  61. stoi, itos = meta['stoi'], meta['itos']
  62. encode = lambda s: [stoi[c] for c in s]
  63. decode = lambda l: ''.join([itos[i] for i in l])
  64. else:
  65. # ok let's assume gpt-2 encodings by default
  66. print("No meta.pkl found, assuming GPT-2 encodings...")
  67. enc = tiktoken.get_encoding("gpt2")
  68. encode = lambda s: enc.encode(s, allowed_special={"<|endoftext|>"})
  69. decode = lambda l: enc.decode(l)
  70. # encode the beginning of the prompt
  71. if start.startswith('FILE:'):
  72. with open(start[5:], 'r', encoding='utf-8') as f:
  73. start = f.read()
  74. start_ids = encode(start)
  75. x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
  76. # run generation
  77. with torch.no_grad():
  78. with ctx:
  79. for k in range(num_samples):
  80. y = model.generate(x, max_new_tokens, temperature=temperature, top_k=top_k)
  81. print(decode(y[0].tolist()))
  82. print('---------------')
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...