gpt_generate.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # Copyright (c) Sebastian Raschka under Apache License 2.0 (see LICENSE.txt).
  2. # Source for "Build a Large Language Model From Scratch"
  3. # - https://www.manning.com/books/build-a-large-language-model-from-scratch
  4. # Code: https://github.com/rasbt/LLMs-from-scratch
  5. import json
  6. import numpy as np
  7. import os
  8. import urllib.request
  9. # import requests
  10. import tensorflow as tf
  11. import tiktoken
  12. import torch
  13. from tqdm import tqdm
  14. # Import from local files
  15. from previous_chapters import GPTModel
  16. def text_to_token_ids(text, tokenizer):
  17. encoded = tokenizer.encode(text)
  18. encoded_tensor = torch.tensor(encoded).unsqueeze(0) # add batch dimension
  19. return encoded_tensor
  20. def token_ids_to_text(token_ids, tokenizer):
  21. flat = token_ids.squeeze(0) # remove batch dimension
  22. return tokenizer.decode(flat.tolist())
  23. def download_and_load_gpt2(model_size, models_dir):
  24. # Validate model size
  25. allowed_sizes = ("124M", "355M", "774M", "1558M")
  26. if model_size not in allowed_sizes:
  27. raise ValueError(f"Model size not in {allowed_sizes}")
  28. # Define paths
  29. model_dir = os.path.join(models_dir, model_size)
  30. base_url = "https://openaipublic.blob.core.windows.net/gpt-2/models"
  31. filenames = [
  32. "checkpoint", "encoder.json", "hparams.json",
  33. "model.ckpt.data-00000-of-00001", "model.ckpt.index",
  34. "model.ckpt.meta", "vocab.bpe"
  35. ]
  36. # Download files
  37. os.makedirs(model_dir, exist_ok=True)
  38. for filename in filenames:
  39. file_url = os.path.join(base_url, model_size, filename)
  40. file_path = os.path.join(model_dir, filename)
  41. download_file(file_url, file_path)
  42. # Load settings and params
  43. tf_ckpt_path = tf.train.latest_checkpoint(model_dir)
  44. settings = json.load(open(os.path.join(model_dir, "hparams.json")))
  45. params = load_gpt2_params_from_tf_ckpt(tf_ckpt_path, settings)
  46. return settings, params
  47. """
  48. def download_file(url, destination):
  49. # Send a GET request to download the file in streaming mode
  50. response = requests.get(url, stream=True)
  51. # Get the total file size from headers, defaulting to 0 if not present
  52. file_size = int(response.headers.get("content-length", 0))
  53. # Check if file exists and has the same size
  54. if os.path.exists(destination):
  55. file_size_local = os.path.getsize(destination)
  56. if file_size == file_size_local:
  57. print(f"File already exists and is up-to-date: {destination}")
  58. return
  59. # Define the block size for reading the file
  60. block_size = 1024 # 1 Kilobyte
  61. # Initialize the progress bar with total file size
  62. progress_bar_description = url.split("/")[-1] # Extract filename from URL
  63. with tqdm(total=file_size, unit="iB", unit_scale=True, desc=progress_bar_description) as progress_bar:
  64. # Open the destination file in binary write mode
  65. with open(destination, "wb") as file:
  66. # Iterate over the file data in chunks
  67. for chunk in response.iter_content(block_size):
  68. progress_bar.update(len(chunk)) # Update progress bar
  69. file.write(chunk) # Write the chunk to the file
  70. """
  71. def download_file(url, destination):
  72. # Send a GET request to download the file
  73. with urllib.request.urlopen(url) as response:
  74. # Get the total file size from headers, defaulting to 0 if not present
  75. file_size = int(response.headers.get("Content-Length", 0))
  76. # Check if file exists and has the same size
  77. if os.path.exists(destination):
  78. file_size_local = os.path.getsize(destination)
  79. if file_size == file_size_local:
  80. print(f"File already exists and is up-to-date: {destination}")
  81. return
  82. # Define the block size for reading the file
  83. block_size = 1024 # 1 Kilobyte
  84. # Initialize the progress bar with total file size
  85. progress_bar_description = os.path.basename(url) # Extract filename from URL
  86. with tqdm(total=file_size, unit="iB", unit_scale=True, desc=progress_bar_description) as progress_bar:
  87. # Open the destination file in binary write mode
  88. with open(destination, "wb") as file:
  89. # Read the file in chunks and write to destination
  90. while True:
  91. chunk = response.read(block_size)
  92. if not chunk:
  93. break
  94. file.write(chunk)
  95. progress_bar.update(len(chunk)) # Update progress bar
  96. def load_gpt2_params_from_tf_ckpt(ckpt_path, settings):
  97. # Initialize parameters dictionary with empty blocks for each layer
  98. params = {"blocks": [{} for _ in range(settings["n_layer"])]}
  99. # Iterate over each variable in the checkpoint
  100. for name, _ in tf.train.list_variables(ckpt_path):
  101. # Load the variable and remove singleton dimensions
  102. variable_array = np.squeeze(tf.train.load_variable(ckpt_path, name))
  103. # Process the variable name to extract relevant parts
  104. variable_name_parts = name.split("/")[1:] # Skip the 'model/' prefix
  105. # Identify the target dictionary for the variable
  106. target_dict = params
  107. if variable_name_parts[0].startswith("h"):
  108. layer_number = int(variable_name_parts[0][1:])
  109. target_dict = params["blocks"][layer_number]
  110. # Recursively access or create nested dictionaries
  111. for key in variable_name_parts[1:-1]:
  112. target_dict = target_dict.setdefault(key, {})
  113. # Assign the variable array to the last key
  114. last_key = variable_name_parts[-1]
  115. target_dict[last_key] = variable_array
  116. return params
  117. def assign(left, right):
  118. if left.shape != right.shape:
  119. raise ValueError(f"Shape mismatch. Left: {left.shape}, Right: {right.shape}")
  120. return torch.nn.Parameter(torch.tensor(right))
  121. def load_weights_into_gpt(gpt, params):
  122. gpt.pos_emb.weight = assign(gpt.pos_emb.weight, params['wpe'])
  123. gpt.tok_emb.weight = assign(gpt.tok_emb.weight, params['wte'])
  124. for b in range(len(params["blocks"])):
  125. q_w, k_w, v_w = np.split(
  126. (params["blocks"][b]["attn"]["c_attn"])["w"], 3, axis=-1)
  127. gpt.trf_blocks[b].att.W_query.weight = assign(
  128. gpt.trf_blocks[b].att.W_query.weight, q_w.T)
  129. gpt.trf_blocks[b].att.W_key.weight = assign(
  130. gpt.trf_blocks[b].att.W_key.weight, k_w.T)
  131. gpt.trf_blocks[b].att.W_value.weight = assign(
  132. gpt.trf_blocks[b].att.W_value.weight, v_w.T)
  133. q_b, k_b, v_b = np.split(
  134. (params["blocks"][b]["attn"]["c_attn"])["b"], 3, axis=-1)
  135. gpt.trf_blocks[b].att.W_query.bias = assign(
  136. gpt.trf_blocks[b].att.W_query.bias, q_b)
  137. gpt.trf_blocks[b].att.W_key.bias = assign(
  138. gpt.trf_blocks[b].att.W_key.bias, k_b)
  139. gpt.trf_blocks[b].att.W_value.bias = assign(
  140. gpt.trf_blocks[b].att.W_value.bias, v_b)
  141. gpt.trf_blocks[b].att.out_proj.weight = assign(
  142. gpt.trf_blocks[b].att.out_proj.weight,
  143. params["blocks"][b]["attn"]["c_proj"]["w"].T)
  144. gpt.trf_blocks[b].att.out_proj.bias = assign(
  145. gpt.trf_blocks[b].att.out_proj.bias,
  146. params["blocks"][b]["attn"]["c_proj"]["b"])
  147. gpt.trf_blocks[b].ff.layers[0].weight = assign(
  148. gpt.trf_blocks[b].ff.layers[0].weight,
  149. params["blocks"][b]["mlp"]["c_fc"]["w"].T)
  150. gpt.trf_blocks[b].ff.layers[0].bias = assign(
  151. gpt.trf_blocks[b].ff.layers[0].bias,
  152. params["blocks"][b]["mlp"]["c_fc"]["b"])
  153. gpt.trf_blocks[b].ff.layers[2].weight = assign(
  154. gpt.trf_blocks[b].ff.layers[2].weight,
  155. params["blocks"][b]["mlp"]["c_proj"]["w"].T)
  156. gpt.trf_blocks[b].ff.layers[2].bias = assign(
  157. gpt.trf_blocks[b].ff.layers[2].bias,
  158. params["blocks"][b]["mlp"]["c_proj"]["b"])
  159. gpt.trf_blocks[b].norm1.scale = assign(
  160. gpt.trf_blocks[b].norm1.scale,
  161. params["blocks"][b]["ln_1"]["g"])
  162. gpt.trf_blocks[b].norm1.shift = assign(
  163. gpt.trf_blocks[b].norm1.shift,
  164. params["blocks"][b]["ln_1"]["b"])
  165. gpt.trf_blocks[b].norm2.scale = assign(
  166. gpt.trf_blocks[b].norm2.scale,
  167. params["blocks"][b]["ln_2"]["g"])
  168. gpt.trf_blocks[b].norm2.shift = assign(
  169. gpt.trf_blocks[b].norm2.shift,
  170. params["blocks"][b]["ln_2"]["b"])
  171. gpt.final_norm.scale = assign(gpt.final_norm.scale, params["g"])
  172. gpt.final_norm.shift = assign(gpt.final_norm.shift, params["b"])
  173. gpt.out_head.weight = assign(gpt.out_head.weight, params["wte"])
  174. def generate(model, idx, max_new_tokens, context_size, temperature=0.0, top_k=None, eos_id=None):
  175. # For-loop is the same as before: Get logits, and only focus on last time step
  176. for _ in range(max_new_tokens):
  177. idx_cond = idx[:, -context_size:]
  178. with torch.no_grad():
  179. logits = model(idx_cond)
  180. logits = logits[:, -1, :]
  181. # New: Filter logits with top_k sampling
  182. if top_k is not None:
  183. # Keep only top_k values
  184. top_logits, _ = torch.topk(logits, top_k)
  185. min_val = top_logits[:, -1]
  186. logits = torch.where(logits < min_val, torch.tensor(float('-inf')).to(logits.device), logits)
  187. # New: Apply temperature scaling
  188. if temperature > 0.0:
  189. logits = logits / temperature
  190. # Apply softmax to get probabilities
  191. probs = torch.softmax(logits, dim=-1) # (batch_size, context_len)
  192. # Sample from the distribution
  193. idx_next = torch.multinomial(probs, num_samples=1) # (batch_size, 1)
  194. # Otherwise same as before: get idx of the vocab entry with the highest logits value
  195. else:
  196. idx_next = torch.argmax(logits, dim=-1, keepdim=True) # (batch_size, 1)
  197. if idx_next == eos_id: # Stop generating early if end-of-sequence token is encountered and eos_id is specified
  198. break
  199. # Same as before: append sampled index to the running sequence
  200. idx = torch.cat((idx, idx_next), dim=1) # (batch_size, num_tokens+1)
  201. return idx
  202. def main(gpt_config, input_prompt, model_size):
  203. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  204. settings, params = download_and_load_gpt2(model_size=model_size, models_dir="gpt2")
  205. gpt = GPTModel(gpt_config)
  206. load_weights_into_gpt(gpt, params)
  207. gpt.to(device)
  208. gpt.eval()
  209. tokenizer = tiktoken.get_encoding("gpt2")
  210. torch.manual_seed(123)
  211. token_ids = generate(
  212. model=gpt,
  213. idx=text_to_token_ids(input_prompt, tokenizer),
  214. max_new_tokens=25,
  215. context_size=gpt_config["context_length"],
  216. top_k=50,
  217. temperature=1.0
  218. )
  219. print("Output text:\n", token_ids_to_text(token_ids, tokenizer))
  220. if __name__ == "__main__":
  221. torch.manual_seed(123)
  222. CHOOSE_MODEL = "gpt2-small (124M)"
  223. INPUT_PROMPT = "Every effort moves you"
  224. BASE_CONFIG = {
  225. "vocab_size": 50257, # Vocabulary size
  226. "context_length": 1024, # Context length
  227. "drop_rate": 0.0, # Dropout rate
  228. "qkv_bias": True # Query-key-value bias
  229. }
  230. model_configs = {
  231. "gpt2-small (124M)": {"emb_dim": 768, "n_layers": 12, "n_heads": 12},
  232. "gpt2-medium (355M)": {"emb_dim": 1024, "n_layers": 24, "n_heads": 16},
  233. "gpt2-large (774M)": {"emb_dim": 1280, "n_layers": 36, "n_heads": 20},
  234. "gpt2-xl (1558M)": {"emb_dim": 1600, "n_layers": 48, "n_heads": 25},
  235. }
  236. model_size = CHOOSE_MODEL.split(" ")[-1].lstrip("(").rstrip(")")
  237. BASE_CONFIG.update(model_configs[CHOOSE_MODEL])
  238. main(BASE_CONFIG, INPUT_PROMPT, model_size)