Skip to content

Commit 1ecdc18

Browse files
committed
Specify UTF-8 encoding in the json load command explicitely
1 parent 5fc78ff commit 1ecdc18

File tree

7 files changed

+40
-25
lines changed

7 files changed

+40
-25
lines changed

appendix-E/01_main-chapter-code/gpt_download.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def download_and_load_gpt2(model_size, models_dir):
4040

4141
# Load settings and params
4242
tf_ckpt_path = tf.train.latest_checkpoint(model_dir)
43-
settings = json.load(open(os.path.join(model_dir, "hparams.json")))
43+
settings = json.load(open(os.path.join(model_dir, "hparams.json"), "r", encoding="utf-8"))
4444
params = load_gpt2_params_from_tf_ckpt(tf_ckpt_path, settings)
4545

4646
return settings, params

ch05/01_main-chapter-code/gpt_download.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def download_and_load_gpt2(model_size, models_dir):
4040

4141
# Load settings and params
4242
tf_ckpt_path = tf.train.latest_checkpoint(model_dir)
43-
settings = json.load(open(os.path.join(model_dir, "hparams.json")))
43+
settings = json.load(open(os.path.join(model_dir, "hparams.json"), "r", encoding="utf-8"))
4444
params = load_gpt2_params_from_tf_ckpt(tf_ckpt_path, settings)
4545

4646
return settings, params

ch05/09_extending-tokenizers/gpt_download.py

+34-19
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ def download_and_load_gpt2(model_size, models_dir):
2323
# Define paths
2424
model_dir = os.path.join(models_dir, model_size)
2525
base_url = "https://openaipublic.blob.core.windows.net/gpt-2/models"
26+
backup_base_url = "https://f001.backblazeb2.com/file/LLMs-from-scratch/gpt2"
2627
filenames = [
2728
"checkpoint", "encoder.json", "hparams.json",
2829
"model.ckpt.data-00000-of-00001", "model.ckpt.index",
@@ -33,22 +34,21 @@ def download_and_load_gpt2(model_size, models_dir):
3334
os.makedirs(model_dir, exist_ok=True)
3435
for filename in filenames:
3536
file_url = os.path.join(base_url, model_size, filename)
37+
backup_url = os.path.join(backup_base_url, model_size, filename)
3638
file_path = os.path.join(model_dir, filename)
37-
download_file(file_url, file_path)
39+
download_file(file_url, file_path, backup_url)
3840

3941
# Load settings and params
4042
tf_ckpt_path = tf.train.latest_checkpoint(model_dir)
41-
settings = json.load(open(os.path.join(model_dir, "hparams.json")))
43+
settings = json.load(open(os.path.join(model_dir, "hparams.json"), "r", encoding="utf-8"))
4244
params = load_gpt2_params_from_tf_ckpt(tf_ckpt_path, settings)
4345

4446
return settings, params
4547

4648

47-
def download_file(url, destination):
48-
# Send a GET request to download the file
49-
50-
try:
51-
with urllib.request.urlopen(url) as response:
49+
def download_file(url, destination, backup_url=None):
50+
def _attempt_download(download_url):
51+
with urllib.request.urlopen(download_url) as response:
5252
# Get the total file size from headers, defaulting to 0 if not present
5353
file_size = int(response.headers.get("Content-Length", 0))
5454

@@ -57,29 +57,44 @@ def download_file(url, destination):
5757
file_size_local = os.path.getsize(destination)
5858
if file_size == file_size_local:
5959
print(f"File already exists and is up-to-date: {destination}")
60-
return
60+
return True # Indicate success without re-downloading
6161

62-
# Define the block size for reading the file
6362
block_size = 1024 # 1 Kilobyte
6463

6564
# Initialize the progress bar with total file size
66-
progress_bar_description = os.path.basename(url) # Extract filename from URL
65+
progress_bar_description = os.path.basename(download_url)
6766
with tqdm(total=file_size, unit="iB", unit_scale=True, desc=progress_bar_description) as progress_bar:
68-
# Open the destination file in binary write mode
6967
with open(destination, "wb") as file:
70-
# Read the file in chunks and write to destination
7168
while True:
7269
chunk = response.read(block_size)
7370
if not chunk:
7471
break
7572
file.write(chunk)
76-
progress_bar.update(len(chunk)) # Update progress bar
77-
except urllib.error.HTTPError:
78-
s = (
79-
f"The specified URL ({url}) is incorrect, the internet connection cannot be established,"
80-
"\nor the requested file is temporarily unavailable.\nPlease visit the following website"
81-
" for help: https://github.com/rasbt/LLMs-from-scratch/discussions/273")
82-
print(s)
73+
progress_bar.update(len(chunk))
74+
return True
75+
76+
try:
77+
if _attempt_download(url):
78+
return
79+
except (urllib.error.HTTPError, urllib.error.URLError):
80+
if backup_url is not None:
81+
print(f"Primary URL ({url}) failed. Attempting backup URL: {backup_url}")
82+
try:
83+
if _attempt_download(backup_url):
84+
return
85+
except urllib.error.HTTPError:
86+
pass
87+
88+
# If we reach here, both attempts have failed
89+
error_message = (
90+
f"Failed to download from both primary URL ({url})"
91+
f"{' and backup URL (' + backup_url + ')' if backup_url else ''}."
92+
"\nCheck your internet connection or the file availability.\n"
93+
"For help, visit: https://github.com/rasbt/LLMs-from-scratch/discussions/273"
94+
)
95+
print(error_message)
96+
except Exception as e:
97+
print(f"An unexpected error occurred: {e}")
8398

8499

85100
# Alternative way using `requests`

ch06/01_main-chapter-code/gpt_download.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def download_and_load_gpt2(model_size, models_dir):
4040

4141
# Load settings and params
4242
tf_ckpt_path = tf.train.latest_checkpoint(model_dir)
43-
settings = json.load(open(os.path.join(model_dir, "hparams.json")))
43+
settings = json.load(open(os.path.join(model_dir, "hparams.json"), "r", encoding="utf-8"))
4444
params = load_gpt2_params_from_tf_ckpt(tf_ckpt_path, settings)
4545

4646
return settings, params

ch06/02_bonus_additional-experiments/gpt_download.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def download_and_load_gpt2(model_size, models_dir):
4040

4141
# Load settings and params
4242
tf_ckpt_path = tf.train.latest_checkpoint(model_dir)
43-
settings = json.load(open(os.path.join(model_dir, "hparams.json")))
43+
settings = json.load(open(os.path.join(model_dir, "hparams.json"), "r", encoding="utf-8"))
4444
params = load_gpt2_params_from_tf_ckpt(tf_ckpt_path, settings)
4545

4646
return settings, params

ch06/03_bonus_imdb-classification/gpt_download.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def download_and_load_gpt2(model_size, models_dir):
4040

4141
# Load settings and params
4242
tf_ckpt_path = tf.train.latest_checkpoint(model_dir)
43-
settings = json.load(open(os.path.join(model_dir, "hparams.json")))
43+
settings = json.load(open(os.path.join(model_dir, "hparams.json"), "r", encoding="utf-8"))
4444
params = load_gpt2_params_from_tf_ckpt(tf_ckpt_path, settings)
4545

4646
return settings, params

ch07/01_main-chapter-code/gpt_download.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def download_and_load_gpt2(model_size, models_dir):
4040

4141
# Load settings and params
4242
tf_ckpt_path = tf.train.latest_checkpoint(model_dir)
43-
settings = json.load(open(os.path.join(model_dir, "hparams.json")))
43+
settings = json.load(open(os.path.join(model_dir, "hparams.json"), "r", encoding="utf-8"))
4444
params = load_gpt2_params_from_tf_ckpt(tf_ckpt_path, settings)
4545

4646
return settings, params

0 commit comments

Comments
 (0)