Datasets:

Languages:
English
Tags:
Not-For-All-Audiences
License:
Gaeros commited on
Commit
1f6bb35
1 Parent(s): 1081ee7

query_tags: cache global pca

Browse files
Files changed (1) hide show
  1. query_tags.py +37 -9
query_tags.py CHANGED
@@ -3,8 +3,7 @@ from pathlib import Path
3
  import argparse
4
 
5
  import numpy as np
6
- import safetensors
7
- from sklearn.decomposition import PCA
8
 
9
  from e6db.utils.numpy import load_tags
10
  from e6db.utils import (
@@ -16,10 +15,7 @@ from e6db.utils import (
16
 
17
 
18
  def dothething(args):
19
- with safetensors.safe_open(
20
- args.data_dir / "implicit_tag_factors.safetensors", framework="numpy"
21
- ) as st:
22
- X = st.get_tensor("tag_factors")
23
  N_vocab = X.shape[0]
24
 
25
  tags2id, idx2tag, tag_categories = load_tags(args.data_dir)
@@ -41,7 +37,7 @@ def dothething(args):
41
  rank_tresh = min(N_vocab, int(tag_freq_to_rank(args.min_frequency)))
42
 
43
  # Score and filter
44
- scores = Xt[:rank_tresh] @ Xt[sel_idxs].T
45
  scores[sel_idxs[sel_idxs < rank_tresh], :] = float("-inf") # Mask self-matches
46
  if args.category:
47
  categories = [tag_category2id[cat] for cat in args.category]
@@ -61,6 +57,7 @@ def dothething(args):
61
  if not args.plot_out:
62
  return
63
  from matplotlib import pyplot as plt
 
64
 
65
  # Deduplicate, global top-k
66
  neigh_idxs = np.unique(neigh_idxs)
@@ -74,8 +71,8 @@ def dothething(args):
74
  colors = np.array(tag_categories_colors)[tag_categories[idxs]]
75
 
76
  # Local PCA
77
- X2 = Xt[idxs]
78
- del Xt
79
  X2 = X2 - X2.mean(0)
80
  X2 /= np.linalg.norm(X2, axis=1)[:, None]
81
  X2t = PCA(2).fit_transform(X2)[:, ::-1]
@@ -115,6 +112,37 @@ def dothething(args):
115
  f.savefig(args.plot_out, facecolor="auto")
116
 
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  def parse_args():
119
  parser = argparse.ArgumentParser(
120
  description="Query similar tags and plots a local PCA.\nUse `-o -` to get an interactive plot",
 
3
  import argparse
4
 
5
  import numpy as np
6
+ import safetensors.numpy
 
7
 
8
  from e6db.utils.numpy import load_tags
9
  from e6db.utils import (
 
15
 
16
 
17
  def dothething(args):
18
+ X = load_smoothed(args.data_dir, args.first_pca)
 
 
 
19
  N_vocab = X.shape[0]
20
 
21
  tags2id, idx2tag, tag_categories = load_tags(args.data_dir)
 
37
  rank_tresh = min(N_vocab, int(tag_freq_to_rank(args.min_frequency)))
38
 
39
  # Score and filter
40
+ scores = X[:rank_tresh] @ X[sel_idxs].T
41
  scores[sel_idxs[sel_idxs < rank_tresh], :] = float("-inf") # Mask self-matches
42
  if args.category:
43
  categories = [tag_category2id[cat] for cat in args.category]
 
57
  if not args.plot_out:
58
  return
59
  from matplotlib import pyplot as plt
60
+ from sklearn.decomposition import PCA
61
 
62
  # Deduplicate, global top-k
63
  neigh_idxs = np.unique(neigh_idxs)
 
71
  colors = np.array(tag_categories_colors)[tag_categories[idxs]]
72
 
73
  # Local PCA
74
+ X2 = X[idxs]
75
+ del X
76
  X2 = X2 - X2.mean(0)
77
  X2 /= np.linalg.norm(X2, axis=1)[:, None]
78
  X2t = PCA(2).fit_transform(X2)[:, ::-1]
 
112
  f.savefig(args.plot_out, facecolor="auto")
113
 
114
 
115
+ def load_smoothed(data_dir: Path | str, k: None | int = None):
116
+ """
117
+ Loads the tag embeddings, scale them to unit length and optionally smooth
118
+ them by reducing dimensionality using PCA.
119
+ """
120
+ # Try loading from cache
121
+ data_dir = Path(data_dir)
122
+ pca_cache_path = data_dir / f"implicit_tag_factors_pca{k}.safetensors"
123
+ if k and pca_cache_path.exists():
124
+ with safetensors.safe_open(pca_cache_path, framework="numpy") as st:
125
+ return st.get_tensor(f"tag_factors_pca{k}")
126
+
127
+ # Load raw embeddings
128
+ with safetensors.safe_open(
129
+ data_dir / "implicit_tag_factors.safetensors", framework="numpy"
130
+ ) as st:
131
+ X = st.get_tensor("tag_factors")
132
+ X /= np.linalg.norm(X, axis=1)[:, None]
133
+
134
+ if not k or k >= X.shape[1]:
135
+ return X
136
+
137
+ from sklearn.decomposition import PCA
138
+
139
+ pca = PCA(k)
140
+ X = pca.fit_transform(X)
141
+ X /= np.linalg.norm(X, axis=1)[:, None]
142
+ safetensors.numpy.save_file({f"tag_factors_pca{k}": X}, pca_cache_path)
143
+ return X
144
+
145
+
146
  def parse_args():
147
  parser = argparse.ArgumentParser(
148
  description="Query similar tags and plots a local PCA.\nUse `-o -` to get an interactive plot",