Skip to content

Commit 4883bed

Browse files
committed
Use pathlib more and have default cache paths be relative to the repo directory
1 parent a9ca974 commit 4883bed

10 files changed

Lines changed: 41 additions & 36 deletions

intervention/appendix_plots.ipynb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"outputs": [],
88
"source": [
99
"# %%\n",
10+
"from pathlib import Path\n",
1011
"import numpy as np\n",
1112
"import matplotlib.pyplot as plt\n",
1213
"from task import get_acts, get_acts_pca, get_all_acts\n",
@@ -462,7 +463,7 @@
462463
"\n",
463464
"for task_name in [\"days_of_week\", \"months_of_year\"]:\n",
464465
" results_mistral = pd.read_csv(\n",
465-
" f\"{BASE_DIR}/mistral_{task_name}/results.csv\", skipinitialspace=True\n",
466+
" Path(BASE_DIR) / f\"mistral_{task_name}\" / \"results.csv\", skipinitialspace=True\n",
466467
" )\n",
467468
"\n",
468469
" results_mistral = results_mistral.rename(\n",
@@ -480,7 +481,7 @@
480481
" print(sum(results_mistral[\"mistral_correct\"]))\n",
481482
"\n",
482483
" results_llama = pd.read_csv(\n",
483-
" f\"{BASE_DIR}/llama_{task_name}/results.csv\", skipinitialspace=True\n",
484+
" Path(BASE_DIR) / f\"llama_{task_name}\" / \"results.csv\", skipinitialspace=True\n",
484485
" )\n",
485486
"\n",
486487
" results_llama = results_llama.rename(\n",

intervention/circle_probe_interventions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@
171171
probe_projections = {}
172172
target_to_embeddings = {}
173173

174-
os.makedirs(f"{task.prefix}/circle_probes_{circle_letter}", exist_ok=True)
174+
(task.prefix / f"circle_probes_{circle_letter}").mkdir(exist_ok=True)
175175

176176
all_maes = []
177177
all_r_squareds = []
@@ -262,7 +262,7 @@
262262
"probe_r": probe_r,
263263
"target_to_embedding": target_to_embedding,
264264
},
265-
f"{task.prefix}/circle_probes_{circle_letter}/{probe_file_extension}_layer_{layer}_token_{token}_pca_{pca_k}.pt",
265+
task.prefix / f"circle_probes_{circle_letter}" / f"{probe_file_extension}_layer_{layer}_token_{token}_pca_{pca_k}.pt",
266266
)
267267

268268
mae = (predictions - multid_targets_train).abs().mean()

intervention/days_of_week_task.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# %%
22

3+
from pathlib import Path
34
import os
45
from utils import setup_notebook, BASE_DIR
56

@@ -49,9 +50,8 @@ def __init__(self, device, model_name="mistral", n_devices=None):
4950
# Tokens we expect as possible answers. Best of these can optionally be saved (as opposed to best logit overall)
5051
self.allowable_tokens = days_of_week
5152

52-
self.prefix = f"{BASE_DIR}{model_name}_days_of_week/"
53-
if not os.path.exists(self.prefix):
54-
os.makedirs(self.prefix)
53+
self.prefix = Path(BASE_DIR) / f"{model_name}_days_of_week"
54+
self.prefix.mkdir(parents=True, exist_ok=True)
5555

5656
self.num_tokens_in_answer = 1
5757

intervention/intervene_in_middle_of_circle.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def vary_wthin_circle(circle_letter, duration, layer, token, pca_k, all_points):
4040
model = task.get_model()
4141

4242
circle_projection_qr = torch.load(
43-
f"{task.prefix}/circle_probes_{circle_letter}/cos_sin_layer_{layer}_token_{token}_pca_{pca_k}.pt"
43+
task.prefix / f"circle_probes_{circle_letter}" / f"cos_sin_layer_{layer}_token_{token}_pca_{pca_k}.pt"
4444
)
4545

4646
for problem in task.generate_problems():

intervention/main_text_plots.ipynb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"outputs": [],
88
"source": [
99
"# %%\n",
10+
"from pathlib import Path\n",
1011
"import numpy as np\n",
1112
"import matplotlib.pyplot as plt\n",
1213
"from task import get_acts, get_acts_pca\n",
@@ -516,7 +517,7 @@
516517
"for task_name in [\"days_of_week\", \"months_of_year\"]:\n",
517518
" for model_name in [\"mistral\", \"llama\"]:\n",
518519
" results = pd.read_csv(\n",
519-
" f\"{BASE_DIR}/{model_name}_{task_name}/results.csv\", skipinitialspace=True\n",
520+
" Path(BASE_DIR) / f\"{model_name}_{task_name}\" / \"results.csv\", skipinitialspace=True\n",
520521
" )\n",
521522
" number_correct = results[\"best_token\"] == results[\"ground_truth\"]\n",
522523
" print(task_name, model_name, np.sum(number_correct))\n",
@@ -560,7 +561,7 @@
560561
"name": "python",
561562
"nbconvert_exporter": "python",
562563
"pygments_lexer": "ipython3",
563-
"version": "3.11.7"
564+
"version": "3.11.9"
564565
}
565566
},
566567
"nbformat": 4,

intervention/months_of_year_task.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# %%
22

33
import os
4+
from pathlib import Path
45
from utils import setup_notebook, BASE_DIR
56

67
setup_notebook()
@@ -71,9 +72,8 @@ def __init__(self, device, model_name="mistral", n_devices=None):
7172
# Tokens we expect as possible answers. Best of these can optionally be saved (as opposed to best logit overall)
7273
self.allowable_tokens = months_of_year
7374

74-
self.prefix = f"{BASE_DIR}{model_name}_months_of_year/"
75-
if not os.path.exists(self.prefix):
76-
os.makedirs(self.prefix)
75+
self.prefix = Path(BASE_DIR) / "{model_name}_months_of_year"
76+
self.prefix.mkdir(parents=True, exist_ok=True)
7777

7878
self.num_tokens_in_answer = 1
7979

intervention/task.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from pathlib import Path
12
from utils import BASE_DIR # Need this import to set the huggingface cache directory
23
import os
34
import numpy as np
@@ -24,7 +25,6 @@ def __str__(self):
2425
def __repr__(self):
2526
return str(self)
2627

27-
2828
def generate_and_save_acts(
2929
task,
3030
names_filter,
@@ -39,10 +39,10 @@ def generate_and_save_acts(
3939
forward_batch_size = 2
4040
num_tokens_to_generate = task.num_tokens_in_answer
4141
all_problems = task.generate_problems()
42-
output_file = task.prefix + "results.csv"
42+
output_file = task.prefix / "results.csv"
4343

4444
if save_results_csv:
45-
os.makedirs(task.prefix, exist_ok=True)
45+
task.prefix.mkdir(parents=True, exist_ok=True)
4646
model_best_addition = "" if not save_best_logit else ", best_token"
4747
with open(output_file, "w") as f:
4848
f.write(
@@ -98,7 +98,7 @@ def generate_and_save_acts(
9898
print(tensors.shape)
9999
torch.save(
100100
tensors,
101-
f"{task.prefix}{save_file_prefix}{current_problem_index}.pt",
101+
task.prefix / f"{save_file_prefix}{current_problem_index}.pt",
102102
)
103103

104104
if save_results_csv:
@@ -146,7 +146,7 @@ def get_all_acts(
146146
all_problems = task.generate_problems()
147147
all_problems_already_generated = True
148148
for i in range(len(all_problems)):
149-
if not os.path.exists(f"{task.prefix}{save_file_prefix}{i}.pt"):
149+
if not (task.prefix / f"{save_file_prefix}{i}.pt").exists():
150150
all_problems_already_generated = False
151151
break
152152
if not all_problems_already_generated or force_regenerate:
@@ -163,7 +163,7 @@ def get_all_acts(
163163
all_acts = []
164164
for i in range(0, len(all_problems)):
165165
tensors = torch.load(
166-
f"{task.prefix}{save_file_prefix}{i}.pt", map_location="cpu"
166+
task.prefix / f"{save_file_prefix}{i}.pt", map_location="cpu"
167167
)
168168
all_acts.append(tensors)
169169
if len(all_acts) > 1:
@@ -186,17 +186,17 @@ def get_acts(
186186
if save_file_prefix != "" and save_file_prefix[-1] != "_":
187187
save_file_prefix += "_"
188188
file_name = (
189-
f"{task.prefix}{save_file_prefix}layer{layer_fetch}_token{token_fetch}.pt"
189+
task.prefix / f"{save_file_prefix}layer{layer_fetch}_token{token_fetch}.pt"
190190
)
191-
if not os.path.exists(file_name) or force_regenerate:
191+
if not file_name.exists() or force_regenerate:
192192
print(file_name, "not exists")
193193
all_acts = get_all_acts(
194194
task, names_filter=names_filter, save_file_prefix=save_file_prefix
195195
)
196196
for layer in range(all_acts.shape[1]):
197197
for token in range(all_acts.shape[2]):
198198
file_name = (
199-
f"{task.prefix}{save_file_prefix}layer{layer}_token{token}.pt"
199+
task.prefix / f"{save_file_prefix}layer{layer}_token{token}.pt"
200200
)
201201
torch.save(
202202
all_acts[:, layer, token, :].detach().cpu().clone(), file_name
@@ -218,11 +218,11 @@ def get_acts_pca(
218218
names_filter=lambda x: "resid_post" in x or "hook_embed" in x,
219219
save_file_prefix="",
220220
):
221-
act_file_name = f"{task.prefix}pca/{save_file_prefix}/layer{layer}_token{token}_pca{pca_k}{'_normalize' if normalize_rms else ''}.pt"
222-
pca_pkl_file_name = f"{task.prefix}pca/{save_file_prefix}/layer{layer}_token{token}_pca{pca_k}{'_normalize' if normalize_rms else ''}.pkl"
223-
os.makedirs(f"{task.prefix}/pca/{save_file_prefix}", exist_ok=True)
221+
act_file_name = task.prefix / "pca" / save_file_prefix / f"layer{layer}_token{token}_pca{pca_k}{'_normalize' if normalize_rms else ''}.pt"
222+
pca_pkl_file_name = task.prefix / "pca" / save_file_prefix / f"layer{layer}_token{token}_pca{pca_k}{'_normalize' if normalize_rms else ''}.pkl"
223+
(task.prefix / "pca" / save_file_prefix).mkdir(parents=True, exist_ok=True)
224224

225-
if not os.path.exists(act_file_name) or not os.path.exists(pca_pkl_file_name):
225+
if not act_file_name.exists() or not pca_pkl_file_name.exists():
226226
acts = get_acts(
227227
task,
228228
layer,
@@ -239,9 +239,9 @@ def get_acts_pca(
239239

240240

241241
def get_acts_pls(task, layer, token, pls_k, normalize_rms=False):
242-
act_file_name = f"{task.prefix}/pls/layer{layer}_token{token}_pls{pls_k}{'_normalize' if normalize_rms else ''}.pt"
243-
pls_pkl_file_name = f"{task.prefix}/pls/layer{layer}_token{token}_pls{pls_k}{'_normalize' if normalize_rms else ''}.pkl"
244-
os.makedirs(f"{task.prefix}/pls", exist_ok=True)
242+
act_file_name = task.prefix / "pls" / f"layer{layer}_token{token}_pls{pls_k}{'_normalize' if normalize_rms else ''}.pt"
243+
pls_pkl_file_name = task.prefix / "pls" / f"layer{layer}_token{token}_pls{pls_k}{'_normalize' if normalize_rms else ''}.pkl"
244+
(task.prefix / "pls").mkdir(parents=True, exist_ok=True)
245245

246246
# if not os.path.exists(act_file_name) or not os.path.exists(pls_pkl_file_name):
247247
if True:

intervention/utils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import os
22
import dill as pickle
3+
from pathlib import Path
34

4-
BASE_DIR = "/data/scratch/jae/"
5+
BASE_DIR = Path(__file__).parent.parent / "cache"
56

6-
os.environ["TRANSFORMERS_CACHE"] = f"{BASE_DIR}/.cache/"
7+
os.environ["TRANSFORMERS_CACHE"] = f"{(Path(BASE_DIR) / '.cache').absolute()}/"
78

89

910
def setup_notebook():

sae_multid_feature_discovery/generate_feature_occurence_data.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
# %%
2-
2+
from pathlib import Path
33
import os
44
from utils import BASE_DIR
55

66

77
# hopefully this will help with memory fragmentation
88
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128"
9-
os.environ["TRANSFORMERS_CACHE"] = f"{BASE_DIR}.cache/"
9+
os.environ["TRANSFORMERS_CACHE"] = f"{(Path(BASE_DIR) / '.cache').absolute()}/"
1010

1111
import einops
1212
import numpy as np
@@ -52,8 +52,8 @@
5252

5353
num_sae_activations_to_save = 10**9
5454

55-
save_folder = f"{BASE_DIR}{model_name}"
56-
os.makedirs(save_folder, exist_ok=True)
55+
save_folder = Path(BASE_DIR) / model_name
56+
save_folder.mkdir(exist_ok=True, parents=True)
5757

5858
t.set_grad_enabled(False)
5959

sae_multid_feature_discovery/utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
2+
from pathlib import Path
13
from huggingface_hub import hf_hub_download
24
import os
35

4-
BASE_DIR = "/data/scratch/jae/"
6+
BASE_DIR = Path(__file__).parent.parent / "cache"
57

68
def get_gpt2_sae(device, layer):
79
from sae_lens import SAE

0 commit comments

Comments
 (0)