gpt_download.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import os
  2. import requests
  3. import json
  4. import numpy as np
  5. import tensorflow as tf
  6. from tqdm import tqdm
  7. def download_and_load_gpt2(model_size, models_dir):
  8. # Validate model size
  9. allowed_sizes = ("124M", "355M", "774M", "1558M")
  10. if model_size not in allowed_sizes:
  11. raise ValueError(f"Model size not in {allowed_sizes}")
  12. # Define paths
  13. model_dir = os.path.join(models_dir, model_size)
  14. base_url = "https://openaipublic.blob.core.windows.net/gpt-2/models"
  15. filenames = [
  16. "checkpoint", "encoder.json", "settings.json",
  17. "model.ckpt.data-00000-of-00001", "model.ckpt.index",
  18. "model.ckpt.meta", "vocab.bpe"
  19. ]
  20. # Download files
  21. os.makedirs(model_dir, exist_ok=True)
  22. for filename in filenames:
  23. file_url = os.path.join(base_url, model_size, filename)
  24. file_path = os.path.join(model_dir, filename)
  25. download_file(file_url, file_path)
  26. # Load settings and params
  27. tf_ckpt_path = tf.train.latest_checkpoint(model_dir)
  28. settings = json.load(open(os.path.join(model_dir, "settings.json")))
  29. params = load_gpt2_params_from_tf_ckpt(tf_ckpt_path, settings)
  30. return settings, params
  31. def download_file(url, destination):
  32. # Send a GET request to download the file in streaming mode
  33. response = requests.get(url, stream=True)
  34. # Get the total file size from headers, defaulting to 0 if not present
  35. file_size = int(response.headers.get("content-length", 0))
  36. # Check if file exists and has the same size
  37. if os.path.exists(destination):
  38. file_size_local = os.path.getsize(destination)
  39. if file_size == file_size_local:
  40. print(f"File already exists and is up-to-date: {destination}")
  41. return
  42. # Define the block size for reading the file
  43. block_size = 1024 # 1 Kilobyte
  44. # Initialize the progress bar with total file size
  45. progress_bar_description = url.split("/")[-1] # Extract filename from URL
  46. with tqdm(total=file_size, unit="iB", unit_scale=True, desc=progress_bar_description) as progress_bar:
  47. # Open the destination file in binary write mode
  48. with open(destination, "wb") as file:
  49. # Iterate over the file data in chunks
  50. for chunk in response.iter_content(block_size):
  51. progress_bar.update(len(chunk)) # Update progress bar
  52. file.write(chunk) # Write the chunk to the file
  53. def load_gpt2_params_from_tf_ckpt(ckpt_path, settings):
  54. # Initialize parameters dictionary with empty blocks for each layer
  55. params = {"blocks": [{} for _ in range(settings["n_layer"])]}
  56. # Iterate over each variable in the checkpoint
  57. for name, _ in tf.train.list_variables(ckpt_path):
  58. # Load the variable and remove singleton dimensions
  59. variable_array = np.squeeze(tf.train.load_variable(ckpt_path, name))
  60. # Process the variable name to extract relevant parts
  61. variable_name_parts = name.split("/")[1:] # Skip the 'model/' prefix
  62. # Identify the target dictionary for the variable
  63. target_dict = params
  64. if variable_name_parts[0].startswith("h"):
  65. layer_number = int(variable_name_parts[0][1:])
  66. target_dict = params["blocks"][layer_number]
  67. # Recursively access or create nested dictionaries
  68. for key in variable_name_parts[1:-1]:
  69. target_dict = target_dict.setdefault(key, {})
  70. # Assign the variable array to the last key
  71. last_key = variable_name_parts[-1]
  72. target_dict[last_key] = variable_array
  73. return params