Skip to content

Commit 7010908

Browse files
authored
Add backup URL for gpt2 weights (rasbt#469)
* Add backup URL for gpt2 weights * newline
1 parent 9b95557 commit 7010908

File tree

8 files changed

+399
-141
lines changed

8 files changed

+399
-141
lines changed

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

+33-18
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,8 +34,9 @@ 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)
@@ -44,11 +46,9 @@ def download_and_load_gpt2(model_size, models_dir):
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`

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

+33-18
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,8 +34,9 @@ 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)
@@ -44,11 +46,9 @@ def download_and_load_gpt2(model_size, models_dir):
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`

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

+36-33
Original file line numberDiff line numberDiff line change
@@ -63,36 +63,39 @@ def check_file_size(url, expected_size):
6363

6464

6565
def test_model_files():
66-
base_url = "https://openaipublic.blob.core.windows.net/gpt-2/models"
67-
68-
model_size = "124M"
69-
files = {
70-
"checkpoint": 77,
71-
"encoder.json": 1042301,
72-
"hparams.json": 90,
73-
"model.ckpt.data-00000-of-00001": 497759232,
74-
"model.ckpt.index": 5215,
75-
"model.ckpt.meta": 471155,
76-
"vocab.bpe": 456318
77-
}
78-
79-
for file_name, expected_size in files.items():
80-
url = f"{base_url}/{model_size}/{file_name}"
81-
valid, message = check_file_size(url, expected_size)
82-
assert valid, message
83-
84-
model_size = "355M"
85-
files = {
86-
"checkpoint": 77,
87-
"encoder.json": 1042301,
88-
"hparams.json": 91,
89-
"model.ckpt.data-00000-of-00001": 1419292672,
90-
"model.ckpt.index": 10399,
91-
"model.ckpt.meta": 926519,
92-
"vocab.bpe": 456318
93-
}
94-
95-
for file_name, expected_size in files.items():
96-
url = f"{base_url}/{model_size}/{file_name}"
97-
valid, message = check_file_size(url, expected_size)
98-
assert valid, message
66+
def check_model_files(base_url):
67+
68+
model_size = "124M"
69+
files = {
70+
"checkpoint": 77,
71+
"encoder.json": 1042301,
72+
"hparams.json": 90,
73+
"model.ckpt.data-00000-of-00001": 497759232,
74+
"model.ckpt.index": 5215,
75+
"model.ckpt.meta": 471155,
76+
"vocab.bpe": 456318
77+
}
78+
79+
for file_name, expected_size in files.items():
80+
url = f"{base_url}/{model_size}/{file_name}"
81+
valid, message = check_file_size(url, expected_size)
82+
assert valid, message
83+
84+
model_size = "355M"
85+
files = {
86+
"checkpoint": 77,
87+
"encoder.json": 1042301,
88+
"hparams.json": 91,
89+
"model.ckpt.data-00000-of-00001": 1419292672,
90+
"model.ckpt.index": 10399,
91+
"model.ckpt.meta": 926519,
92+
"vocab.bpe": 456318
93+
}
94+
95+
for file_name, expected_size in files.items():
96+
url = f"{base_url}/{model_size}/{file_name}"
97+
valid, message = check_file_size(url, expected_size)
98+
assert valid, message
99+
100+
check_model_files(base_url="https://openaipublic.blob.core.windows.net/gpt-2/models")
101+
check_model_files(base_url="https://f001.backblazeb2.com/file/LLMs-from-scratch/gpt2")

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

+33-18
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,8 +34,9 @@ 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)
@@ -44,11 +46,9 @@ def download_and_load_gpt2(model_size, models_dir):
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`

0 commit comments

Comments
 (0)