miwytt commited on
Commit
0ddf935
·
1 Parent(s): 47bd969

adopted changes from package

Browse files
README.md CHANGED
@@ -17,7 +17,7 @@ preload:
17
 
18
  # CTFAlign · Document-level Word Alignment — demo
19
 
20
- Interactive demo for [CTFAlign](https://github.com/miwytt/doc-wordalign): choose one of the models from the paper's experiments, paste a document pair, and see the predicted word alignments. Hover a word to highlight its aligned counterpart(s) in the other text.
21
 
22
  - **Model** — experiment models with a document-level tuned layer: Qwen3-Embedding-4B (default), LaBSE, mmBERT-base.
23
  - **Method** — `ctfalign` (default) or `mdpalign`.
 
17
 
18
  # CTFAlign · Document-level Word Alignment — demo
19
 
20
+ Interactive demo for [CTFAlign](https://github.com/ZurichNLP/CTFAlign): choose one of the models from the paper's experiments, paste a document pair, and see the predicted word alignments. Hover a word to highlight its aligned counterpart(s) in the other text.
21
 
22
  - **Model** — experiment models with a document-level tuned layer: Qwen3-Embedding-4B (default), LaBSE, mmBERT-base.
23
  - **Method** — `ctfalign` (default) or `mdpalign`.
app.py CHANGED
@@ -107,22 +107,7 @@ def _needs_subword(text):
107
  return sum(_is_cjk(c) for c in chars) / len(chars) > 0.2
108
 
109
 
110
- def _subword_units(enc, text):
111
- """Surface strings of the non-special tokens, aligned to the embedding rows."""
112
- tok = enc.tokenizer
113
- e = tok(text, add_special_tokens=True, return_special_tokens_mask=True,
114
- truncation=False)
115
- ids = [i for i, sp in zip(e["input_ids"], e["special_tokens_mask"]) if not sp]
116
- units = []
117
- for t in tok.convert_ids_to_tokens(ids):
118
- s = tok.convert_tokens_to_string([t]).strip() # handles ▁ and byte-level markers
119
- if s.startswith("##"): # WordPiece marker survives single-token decode
120
- s = s[2:]
121
- units.append(s or t)
122
- return units
123
-
124
-
125
- def _units_and_ids(enc, text, encoded, seg):
126
  """Per-side display units and the b2w map fed to ``align_from_similarity``.
127
 
128
  ``seg`` is 'auto' | 'words' | 'subwords'. In subword mode each non-special
@@ -134,11 +119,10 @@ def _units_and_ids(enc, text, encoded, seg):
134
  the alignment indices are meaningless without it.
135
  """
136
  if seg == "subwords" or (seg == "auto" and _needs_subword(text)):
137
- n_tok = int(encoded.embeddings.shape[0])
138
- units = _subword_units(enc, text)
139
- if len(units) != n_tok: # chunked re-tokenisation drift
140
- units = (units + [""] * n_tok)[:n_tok]
141
- return units, list(range(n_tok)), "subword"
142
  return text.split(), encoded.word_ids, "word"
143
 
144
 
@@ -184,16 +168,16 @@ def align_payload(model_display, method_display, mode, lp_choice, layer_in, k_in
184
  enc = _get_encoder(hf_id, layer)
185
  k = float(k_in) if k_in not in (None, "") else None
186
  chunk_size = max(enc.max_length - 2, 1)
187
- n_tok_a = len(enc.tokenizer.encode(text_a, add_special_tokens=False))
188
- n_tok_b = len(enc.tokenizer.encode(text_b, add_special_tokens=False))
189
  # Encode once and share the similarity matrix between the selected method
190
  # and the unconstrained SimAlign baseline (the latter is just an argmax).
191
  a = enc.encode(text_a)
192
  b = enc.encode(text_b)
193
  # Pick units per side: whitespace words, or subwords for non-segmented
194
  # (zh/ja) text — in which case the alignment is left at the token level.
195
- units_a, ids_a, level_a = _units_and_ids(enc, text_a, a, seg)
196
- units_b, ids_b, level_b = _units_and_ids(enc, text_b, b, seg)
197
  sim = get_sim_matrix(a.embeddings, b.embeddings)
198
  pairs = align_from_similarity(sim, ids_a, ids_b,
199
  method=method, mode=mode, k=k)
 
107
  return sum(_is_cjk(c) for c in chars) / len(chars) > 0.2
108
 
109
 
110
+ def _units_and_ids(text, encoded, seg):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  """Per-side display units and the b2w map fed to ``align_from_similarity``.
112
 
113
  ``seg`` is 'auto' | 'words' | 'subwords'. In subword mode each non-special
 
119
  the alignment indices are meaningless without it.
120
  """
121
  if seg == "subwords" or (seg == "auto" and _needs_subword(text)):
122
+ # EncodedText.tokens comes out of the same pass as the embeddings, so it
123
+ # is always row-aligned with them (this is the package's units="tokens").
124
+ units = list(encoded.tokens)
125
+ return units, list(range(len(units))), "subword"
 
126
  return text.split(), encoded.word_ids, "word"
127
 
128
 
 
168
  enc = _get_encoder(hf_id, layer)
169
  k = float(k_in) if k_in not in (None, "") else None
170
  chunk_size = max(enc.max_length - 2, 1)
171
+ n_tok_a = len(enc.tokenizer.encode(text_a, add_special_tokens=False, verbose=False))
172
+ n_tok_b = len(enc.tokenizer.encode(text_b, add_special_tokens=False, verbose=False))
173
  # Encode once and share the similarity matrix between the selected method
174
  # and the unconstrained SimAlign baseline (the latter is just an argmax).
175
  a = enc.encode(text_a)
176
  b = enc.encode(text_b)
177
  # Pick units per side: whitespace words, or subwords for non-segmented
178
  # (zh/ja) text — in which case the alignment is left at the token level.
179
+ units_a, ids_a, level_a = _units_and_ids(text_a, a, seg)
180
+ units_b, ids_b, level_b = _units_and_ids(text_b, b, seg)
181
  sim = get_sim_matrix(a.embeddings, b.embeddings)
182
  pairs = align_from_similarity(sim, ids_a, ids_b,
183
  method=method, mode=mode, k=k)
ctfalign/.DS_Store DELETED
Binary file (6.15 kB)
 
ctfalign/__init__.py CHANGED
@@ -13,6 +13,7 @@ Bring your own embeddings (no framework dependency)::
13
  """
14
  from .aligner import (
15
  METHODS,
 
16
  WordAligner,
17
  align_from_embeddings,
18
  align_from_similarity,
@@ -29,6 +30,7 @@ __all__ = [
29
  "alignment_record",
30
  "to_word_alignment_label_notation",
31
  "METHODS",
 
32
  "EncodedText",
33
  "Encoder",
34
  ]
 
13
  """
14
  from .aligner import (
15
  METHODS,
16
+ UNITS,
17
  WordAligner,
18
  align_from_embeddings,
19
  align_from_similarity,
 
30
  "alignment_record",
31
  "to_word_alignment_label_notation",
32
  "METHODS",
33
+ "UNITS",
34
  "EncodedText",
35
  "Encoder",
36
  ]
ctfalign/__pycache__/__init__.cpython-311.pyc DELETED
Binary file (1.23 kB)
 
ctfalign/__pycache__/align.cpython-311.pyc DELETED
Binary file (4.32 kB)
 
ctfalign/__pycache__/aligner.cpython-311.pyc DELETED
Binary file (8.93 kB)
 
ctfalign/__pycache__/cli.cpython-311.pyc DELETED
Binary file (7.75 kB)
 
ctfalign/__pycache__/defaults.cpython-311.pyc DELETED
Binary file (3.43 kB)
 
ctfalign/__pycache__/masks.cpython-311.pyc DELETED
Binary file (5.85 kB)
 
ctfalign/__pycache__/similarity.cpython-311.pyc DELETED
Binary file (775 Bytes)
 
ctfalign/__pycache__/wordmap.cpython-311.pyc DELETED
Binary file (4.89 kB)
 
ctfalign/align.py CHANGED
@@ -4,11 +4,16 @@ Both functions operate on a single token-level similarity matrix and return a
4
  list of ``(src_token_idx, tgt_token_idx)`` pairs over the *non-special* token
5
  sequence. They are framework-independent: ``argmax_align`` takes a torch tensor,
6
  ``iter_max`` takes a numpy array (matching the SimAlign reference).
 
 
 
 
 
7
  """
8
  import numpy as np
9
 
10
 
11
- def argmax_align(similarity_matrix):
12
  """Greedy bidirectional argmax, intersected (SimAlign argmax)."""
13
  en_cz = similarity_matrix.argmax(dim=1)
14
  cz_en = similarity_matrix.argmax(dim=0)
@@ -17,11 +22,33 @@ def argmax_align(similarity_matrix):
17
  for i, j in enumerate(en_cz):
18
  j = j.item()
19
  if cz_en[j] == i:
 
 
20
  intersection.append((i, j))
21
  return intersection
22
 
23
 
24
- def iter_max(sim_matrix: np.ndarray, max_count: int = 2) -> np.ndarray:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  """Iterative refinement of the argmax intersection (SimAlign itermax).
26
 
27
  ``max_count`` controls the number of iterations; higher means more recall.
@@ -29,28 +56,34 @@ def iter_max(sim_matrix: np.ndarray, max_count: int = 2) -> np.ndarray:
29
  """
30
  alpha_ratio = 0.9
31
  m, n = sim_matrix.shape
32
- forward = np.eye(n)[sim_matrix.argmax(axis=1)] # m x n
33
- backward = np.eye(m)[sim_matrix.argmax(axis=0)] # n x m
34
  inter = forward * backward.transpose()
35
 
36
  if min(m, n) <= 2:
37
  rows, cols = np.where(inter > 0)
38
- return list(zip(rows.tolist(), cols.tolist()))
 
39
 
40
- new_inter = np.zeros((m, n))
41
  count = 1
42
  while count < max_count:
43
- mask_x = 1.0 - np.tile(inter.sum(1)[:, np.newaxis], (1, n)).clip(0.0, 1.0)
44
- mask_y = 1.0 - np.tile(inter.sum(0)[np.newaxis, :], (m, 1)).clip(0.0, 1.0)
 
 
 
 
 
 
 
 
 
45
  mask = ((alpha_ratio * mask_x) + (alpha_ratio * mask_y)).clip(0.0, 1.0)
46
  mask_zeros = 1.0 - ((1.0 - mask_x) * (1.0 - mask_y))
47
- if mask_x.sum() < 1.0 or mask_y.sum() < 1.0:
48
- mask *= 0.0
49
- mask_zeros *= 0.0
50
 
51
  new_sim = sim_matrix * mask
52
- fwd = np.eye(n)[new_sim.argmax(axis=1)] * mask_zeros
53
- bac = np.eye(m)[new_sim.argmax(axis=0)].transpose() * mask_zeros
54
  new_inter = fwd * bac
55
 
56
  if np.array_equal(inter + new_inter, inter):
@@ -58,4 +91,5 @@ def iter_max(sim_matrix: np.ndarray, max_count: int = 2) -> np.ndarray:
58
  inter = inter + new_inter
59
  count += 1
60
  rows, cols = np.where(inter > 0)
61
- return list(zip(rows.tolist(), cols.tolist()))
 
 
4
  list of ``(src_token_idx, tgt_token_idx)`` pairs over the *non-special* token
5
  sequence. They are framework-independent: ``argmax_align`` takes a torch tensor,
6
  ``iter_max`` takes a numpy array (matching the SimAlign reference).
7
+
8
+ Both accept ``drop_negative``: when set, pairs whose similarity is not strictly
9
+ positive are discarded. A negative cosine similarity means the two token
10
+ embeddings point in opposite directions, so it should never license an
11
+ alignment -- even when it happens to be the row/column maximum.
12
  """
13
  import numpy as np
14
 
15
 
16
+ def argmax_align(similarity_matrix, drop_negative=False):
17
  """Greedy bidirectional argmax, intersected (SimAlign argmax)."""
18
  en_cz = similarity_matrix.argmax(dim=1)
19
  cz_en = similarity_matrix.argmax(dim=0)
 
22
  for i, j in enumerate(en_cz):
23
  j = j.item()
24
  if cz_en[j] == i:
25
+ if drop_negative and float(similarity_matrix[i, j]) <= 0:
26
+ continue
27
  intersection.append((i, j))
28
  return intersection
29
 
30
 
31
+ def _keep_positive(pairs, matrix, drop_negative):
32
+ """Drop pairs whose similarity is not strictly positive (see argmax_align)."""
33
+ if not drop_negative:
34
+ return pairs
35
+ return [(i, j) for i, j in pairs if float(matrix[i, j]) > 0]
36
+
37
+
38
+ def _onehot_rows(idx: np.ndarray, n: int) -> np.ndarray:
39
+ """Row-wise one-hot matrix, i.e. ``np.eye(n)[idx]`` without the n x n identity.
40
+
41
+ The identity is a transient the result never keeps: only ``len(idx)`` of its
42
+ rows are gathered. Building the result directly avoids allocating it (at the
43
+ deepest pyramid level of a long document it runs to hundreds of MB).
44
+ """
45
+ out = np.zeros((idx.shape[0], n))
46
+ out[np.arange(idx.shape[0]), idx] = 1.0
47
+ return out
48
+
49
+
50
+ def iter_max(sim_matrix: np.ndarray, max_count: int = 2,
51
+ drop_negative: bool = False) -> np.ndarray:
52
  """Iterative refinement of the argmax intersection (SimAlign itermax).
53
 
54
  ``max_count`` controls the number of iterations; higher means more recall.
 
56
  """
57
  alpha_ratio = 0.9
58
  m, n = sim_matrix.shape
59
+ forward = _onehot_rows(sim_matrix.argmax(axis=1), n) # m x n
60
+ backward = _onehot_rows(sim_matrix.argmax(axis=0), m) # n x m
61
  inter = forward * backward.transpose()
62
 
63
  if min(m, n) <= 2:
64
  rows, cols = np.where(inter > 0)
65
+ return _keep_positive(list(zip(rows.tolist(), cols.tolist())),
66
+ sim_matrix, drop_negative)
67
 
 
68
  count = 1
69
  while count < max_count:
70
+ # mask_x / mask_y are constant along one axis, so they are kept as a
71
+ # column and a row vector and expanded by broadcasting rather than tiled.
72
+ mask_x = 1.0 - inter.sum(1)[:, np.newaxis].clip(0.0, 1.0) # m x 1
73
+ mask_y = 1.0 - inter.sum(0)[np.newaxis, :].clip(0.0, 1.0) # 1 x n
74
+ if mask_x.sum() < 1.0 or mask_y.sum() < 1.0:
75
+ # Every row (or every column) is already aligned. The original
76
+ # zeroed both masks here and ran the iteration out on all-zero
77
+ # arrays, which yields an empty new_inter and breaks on the next
78
+ # equality check regardless -- so break directly.
79
+ break
80
+
81
  mask = ((alpha_ratio * mask_x) + (alpha_ratio * mask_y)).clip(0.0, 1.0)
82
  mask_zeros = 1.0 - ((1.0 - mask_x) * (1.0 - mask_y))
 
 
 
83
 
84
  new_sim = sim_matrix * mask
85
+ fwd = _onehot_rows(new_sim.argmax(axis=1), n) * mask_zeros
86
+ bac = _onehot_rows(new_sim.argmax(axis=0), m).transpose() * mask_zeros
87
  new_inter = fwd * bac
88
 
89
  if np.array_equal(inter + new_inter, inter):
 
91
  inter = inter + new_inter
92
  count += 1
93
  rows, cols = np.where(inter > 0)
94
+ return _keep_positive(list(zip(rows.tolist(), cols.tolist())),
95
+ sim_matrix, drop_negative)
ctfalign/aligner.py CHANGED
@@ -16,9 +16,9 @@ import torch
16
  from .align import argmax_align, iter_max
17
  from .defaults import resolve_k, resolve_layer
18
  from .masks import (
19
- add_belt_mask_token_count_fixed_on_longer_side,
20
- add_soft_belt_mask_token_count_fixed_on_longer_side,
21
- pyramid_hard_lenient2,
22
  )
23
  from .similarity import get_sim_matrix
24
  from .wordmap import project_token_alignment
@@ -32,6 +32,7 @@ _METHOD_ALIASES = {
32
  "ctfalign": "ctfalign",
33
  }
34
  METHODS = ("simalign", "mdpalign-strict", "mdpalign-fuzzy", "ctfalign")
 
35
 
36
 
37
  def _normalize_method(method):
@@ -41,32 +42,46 @@ def _normalize_method(method):
41
  return _METHOD_ALIASES[key]
42
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  def align_from_similarity(sim, word_ids_a, word_ids_b,
45
  method="ctfalign", mode="argmax", k=None, max_count=2):
46
  """Align a pre-computed token similarity matrix to word-level pairs.
47
 
48
  sim : ``(n_tokens_a, n_tokens_b)`` similarity matrix (array-like).
49
- Negative entries are clamped to 0 before masking, matching
50
- the research pipeline.
 
51
  word_ids_a / b : per-token whitespace-word indices (b2w maps).
52
  Returns a sorted list of ``(word_idx_a, word_idx_b)`` pairs.
53
  """
54
  method = _normalize_method(method)
55
  k = resolve_k(method, k)
56
 
57
- sim = torch.as_tensor(sim, dtype=torch.float32).clamp(min=0)
58
 
59
  if method == "mdpalign-strict":
60
- sim = add_belt_mask_token_count_fixed_on_longer_side(sim, k)
61
  elif method == "mdpalign-fuzzy":
62
- sim = add_soft_belt_mask_token_count_fixed_on_longer_side(sim, k)
63
 
64
  if method == "ctfalign":
65
- token_alignment = pyramid_hard_lenient2(sim, f"simalign-{mode}", width=int(k))
66
  elif mode == "argmax":
67
- token_alignment = argmax_align(sim)
68
  elif mode == "itermax":
69
- token_alignment = iter_max(sim.numpy(), max_count=max_count)
 
70
  else:
71
  raise ValueError(f"Unknown mode {mode!r}; use 'argmax' or 'itermax'.")
72
 
@@ -91,19 +106,38 @@ def align_from_embeddings(emb_a, emb_b, word_ids_a, word_ids_b,
91
 
92
 
93
  class WordAligner:
94
- """High-level aligner: encode two texts and return word-level alignments."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
- def __init__(self, encoder, method="ctfalign", mode="argmax", k=None, max_count=2):
 
97
  self.encoder = encoder
98
  self.method = _normalize_method(method)
99
  self.mode = mode
100
  self.k = resolve_k(self.method, k)
101
  self.max_count = max_count
 
102
 
103
  @classmethod
104
  def from_huggingface(cls, model_name, layer=None, lang_pair=None, granularity="documents",
105
  method="ctfalign", mode="argmax", k=None, max_count=2,
106
- device=None, token=None, **encoder_kwargs):
107
  """Build an aligner backed by a HuggingFace model.
108
 
109
  ``layer`` defaults to the empirically-best layer for the model (and
@@ -132,34 +166,79 @@ class WordAligner:
132
  )
133
 
134
  encoder = HFEncoder(model_name, layer, device=device, token=token, **encoder_kwargs)
135
- return cls(encoder, method=method, mode=mode, k=k, max_count=max_count)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
  def align(self, text_a, text_b):
138
- """Return a sorted list of ``(word_idx_a, word_idx_b)`` alignment pairs."""
 
 
 
 
 
 
 
 
 
 
 
 
139
  a = self.encoder.encode(text_a)
140
  b = self.encoder.encode(text_b)
141
- return align_from_embeddings(
142
- a.embeddings, b.embeddings, a.word_ids, b.word_ids,
 
 
143
  method=self.method, mode=self.mode, k=self.k, max_count=self.max_count,
144
  )
 
145
 
146
- def align_pairs(self, pairs, show_progress=False):
 
147
  """Align many text pairs.
148
 
149
  ``pairs``: iterable of ``(text_a, text_b)`` tuples.
150
  Returns a list of per-pair alignments, in input order. Empty/blank texts
151
  yield an empty alignment so positional correspondence is preserved.
 
 
 
 
 
 
 
 
 
152
  """
153
  pairs = list(pairs)
 
 
 
 
154
  results = []
155
  for idx, (text_a, text_b) in enumerate(pairs, 1):
156
  if not text_a.strip() or not text_b.strip():
157
- results.append([])
 
 
158
  else:
159
  results.append(self.align(text_a, text_b))
160
- if show_progress:
161
- print(f"\r aligned {idx}/{len(pairs)} pairs", end="",
162
- file=sys.stderr, flush=True)
163
- if show_progress:
164
- print(file=sys.stderr)
165
  return results
 
16
  from .align import argmax_align, iter_max
17
  from .defaults import resolve_k, resolve_layer
18
  from .masks import (
19
+ apply_mdpalign_strict,
20
+ apply_mdpalign_fuzzy,
21
+ ctfalign,
22
  )
23
  from .similarity import get_sim_matrix
24
  from .wordmap import project_token_alignment
 
32
  "ctfalign": "ctfalign",
33
  }
34
  METHODS = ("simalign", "mdpalign-strict", "mdpalign-fuzzy", "ctfalign")
35
+ UNITS = ("words", "tokens")
36
 
37
 
38
  def _normalize_method(method):
 
42
  return _METHOD_ALIASES[key]
43
 
44
 
45
+ def _normalize_units(units):
46
+ if units not in UNITS:
47
+ raise ValueError(f"Unknown units {units!r}; choose from {UNITS}.")
48
+ return units
49
+
50
+
51
+ def _print_progress(idx, total):
52
+ """Default ``progress_callback`` for ``WordAligner.align_pairs``: prints to stderr."""
53
+ end = "\n" if idx == total else ""
54
+ print(f"\r aligned {idx}/{total} pairs", end=end, file=sys.stderr, flush=True)
55
+
56
+
57
  def align_from_similarity(sim, word_ids_a, word_ids_b,
58
  method="ctfalign", mode="argmax", k=None, max_count=2):
59
  """Align a pre-computed token similarity matrix to word-level pairs.
60
 
61
  sim : ``(n_tokens_a, n_tokens_b)`` similarity matrix (array-like).
62
+ Used as-is: negative entries stay negative (they are
63
+ clamped only within a pooled CTFAlign block, see
64
+ ``masks.py``) and never license an alignment.
65
  word_ids_a / b : per-token whitespace-word indices (b2w maps).
66
  Returns a sorted list of ``(word_idx_a, word_idx_b)`` pairs.
67
  """
68
  method = _normalize_method(method)
69
  k = resolve_k(method, k)
70
 
71
+ sim = torch.as_tensor(sim, dtype=torch.float32)
72
 
73
  if method == "mdpalign-strict":
74
+ sim = apply_mdpalign_strict(sim, k)
75
  elif method == "mdpalign-fuzzy":
76
+ sim = apply_mdpalign_fuzzy(sim, k)
77
 
78
  if method == "ctfalign":
79
+ token_alignment = ctfalign(sim, f"simalign-{mode}", width=int(k))
80
  elif mode == "argmax":
81
+ token_alignment = argmax_align(sim, drop_negative=True)
82
  elif mode == "itermax":
83
+ token_alignment = iter_max(sim.numpy(), max_count=max_count,
84
+ drop_negative=True)
85
  else:
86
  raise ValueError(f"Unknown mode {mode!r}; use 'argmax' or 'itermax'.")
87
 
 
106
 
107
 
108
  class WordAligner:
109
+ """High-level aligner: encode two texts and return their alignment.
110
+
111
+ ``units`` selects what the returned indices point at:
112
+
113
+ ``"words"`` (default)
114
+ Whitespace-split words -- the setting used throughout the paper. Texts in
115
+ languages without whitespace word boundaries (zh, ja, ...) must be
116
+ pre-segmented, as they were for the reported experiments.
117
+ ``"tokens"``
118
+ The encoder's own subword tokens, i.e. no projection to words at all.
119
+ Use this when the input is not whitespace-segmented and pre-segmenting is
120
+ not an option. The indices then point into ``EncodedText.tokens``, which
121
+ ``align_with_units`` returns alongside the pairs.
122
+
123
+ The choice is explicit rather than inferred from the script: guessing would
124
+ silently change the meaning of the output, including for the pre-segmented
125
+ zh/ja inputs the paper's numbers are based on.
126
+ """
127
 
128
+ def __init__(self, encoder, method="ctfalign", mode="argmax", k=None, max_count=2,
129
+ units="words"):
130
  self.encoder = encoder
131
  self.method = _normalize_method(method)
132
  self.mode = mode
133
  self.k = resolve_k(self.method, k)
134
  self.max_count = max_count
135
+ self.units = _normalize_units(units)
136
 
137
  @classmethod
138
  def from_huggingface(cls, model_name, layer=None, lang_pair=None, granularity="documents",
139
  method="ctfalign", mode="argmax", k=None, max_count=2,
140
+ units="words", device=None, token=None, **encoder_kwargs):
141
  """Build an aligner backed by a HuggingFace model.
142
 
143
  ``layer`` defaults to the empirically-best layer for the model (and
 
166
  )
167
 
168
  encoder = HFEncoder(model_name, layer, device=device, token=token, **encoder_kwargs)
169
+ return cls(encoder, method=method, mode=mode, k=k, max_count=max_count,
170
+ units=units)
171
+
172
+ def _units_and_ids(self, text, encoded):
173
+ """The display units for one side and the b2w map to project onto them.
174
+
175
+ In ``"tokens"`` mode the map is the identity, so the token-level
176
+ alignment is returned as-is with no projection.
177
+ """
178
+ if self.units == "words":
179
+ return text.split(), encoded.word_ids
180
+ if encoded.tokens is None:
181
+ raise ValueError(
182
+ f"units='tokens' needs token surface strings, but "
183
+ f"{type(self.encoder).__name__} returned EncodedText(tokens=None). "
184
+ f"Populate EncodedText.tokens in your encoder, or use units='words'."
185
+ )
186
+ return list(encoded.tokens), list(range(len(encoded.tokens)))
187
 
188
  def align(self, text_a, text_b):
189
+ """Return a sorted list of ``(idx_a, idx_b)`` alignment pairs.
190
+
191
+ Indices refer to whitespace words or to encoder tokens, per ``units``.
192
+ """
193
+ return self.align_with_units(text_a, text_b)[0]
194
+
195
+ def align_with_units(self, text_a, text_b):
196
+ """Return ``(pairs, units_a, units_b)`` from a single encoding pass.
197
+
198
+ ``units_a`` / ``units_b`` are the strings the pair indices point at, so
199
+ the alignment is readable without re-deriving the segmentation. Useful in
200
+ ``units="tokens"`` mode, where the indices are otherwise opaque.
201
+ """
202
  a = self.encoder.encode(text_a)
203
  b = self.encoder.encode(text_b)
204
+ units_a, word_ids_a = self._units_and_ids(text_a, a)
205
+ units_b, word_ids_b = self._units_and_ids(text_b, b)
206
+ pairs = align_from_embeddings(
207
+ a.embeddings, b.embeddings, word_ids_a, word_ids_b,
208
  method=self.method, mode=self.mode, k=self.k, max_count=self.max_count,
209
  )
210
+ return pairs, units_a, units_b
211
 
212
+ def align_pairs(self, pairs, show_progress=False, progress_callback=None,
213
+ with_units=False):
214
  """Align many text pairs.
215
 
216
  ``pairs``: iterable of ``(text_a, text_b)`` tuples.
217
  Returns a list of per-pair alignments, in input order. Empty/blank texts
218
  yield an empty alignment so positional correspondence is preserved.
219
+
220
+ ``with_units=True`` returns ``(pairs, units_a, units_b)`` triples instead
221
+ of bare pair lists, without a second encoding pass.
222
+
223
+ ``progress_callback``, if given, is called as ``callback(idx, total)``
224
+ after each pair (1-indexed). ``show_progress=True`` installs a default
225
+ callback that prints ``idx/total`` to stderr; pass your own
226
+ ``progress_callback`` instead for other UIs (e.g. a notebook or a
227
+ different CLI's progress bar).
228
  """
229
  pairs = list(pairs)
230
+ total = len(pairs)
231
+ if progress_callback is None and show_progress:
232
+ progress_callback = _print_progress
233
+
234
  results = []
235
  for idx, (text_a, text_b) in enumerate(pairs, 1):
236
  if not text_a.strip() or not text_b.strip():
237
+ results.append(([], [], []) if with_units else [])
238
+ elif with_units:
239
+ results.append(self.align_with_units(text_a, text_b))
240
  else:
241
  results.append(self.align(text_a, text_b))
242
+ if progress_callback:
243
+ progress_callback(idx, total)
 
 
 
244
  return results
ctfalign/cli.py CHANGED
@@ -7,7 +7,7 @@ import argparse
7
  import json
8
  import sys
9
 
10
- from .aligner import METHODS, WordAligner
11
 
12
 
13
  def to_word_alignment_label_notation(pairs):
@@ -15,15 +15,26 @@ def to_word_alignment_label_notation(pairs):
15
  return " ".join(f"{i}-{j}" for i, j in pairs)
16
 
17
 
18
- def alignment_record(text_a, text_b, pairs, fmt="string"):
 
19
  """Build one JSONL record: original texts plus the alignment labels.
20
 
21
  ``fmt="string"`` encodes the alignment as a word-alignment-label-notation
22
  string (``"0-0 1-1"``); ``fmt="pairs"`` as a list of ``[i, j]`` pairs.
 
 
 
 
 
23
  """
24
  labels = ([list(p) for p in pairs] if fmt == "pairs"
25
  else to_word_alignment_label_notation(pairs))
26
- return {"text_a": text_a, "text_b": text_b, "labels": labels}
 
 
 
 
 
27
 
28
 
29
  def _read_lines(path):
@@ -39,6 +50,7 @@ def cmd_align(args):
39
  granularity=args.granularity,
40
  method=args.method,
41
  k=args.k,
 
42
  device=args.device,
43
  **({"mode": args.mode} if args.mode else {}),
44
  )
@@ -53,9 +65,13 @@ def cmd_align(args):
53
 
54
  out = open(args.output, "w", encoding="utf-8") if args.output else sys.stdout
55
  try:
56
- results = aligner.align_pairs(zip(src, tgt), show_progress=not args.quiet)
57
- for text_a, text_b, pairs in zip(src, tgt, results):
58
- record = alignment_record(text_a, text_b, pairs, fmt=args.label_format)
 
 
 
 
59
  out.write(json.dumps(record, ensure_ascii=False) + "\n")
60
  finally:
61
  if args.output:
@@ -87,6 +103,11 @@ def build_parser():
87
  help="constraint hyperparameter: w blocks (CTFAlign) or k tokens (MDPAlign)")
88
  a.add_argument("--lang-pair", dest="lang_pair",
89
  help="e.g. en-fr, to pick a language-pair-specific tuned layer")
 
 
 
 
 
90
  a.add_argument("--device", help="torch device, e.g. cuda:0 or cpu")
91
  a.add_argument("-o", "--output", help="output JSONL file (default: stdout)")
92
  a.add_argument("--label-format", dest="label_format",
 
7
  import json
8
  import sys
9
 
10
+ from .aligner import METHODS, UNITS, WordAligner
11
 
12
 
13
  def to_word_alignment_label_notation(pairs):
 
15
  return " ".join(f"{i}-{j}" for i, j in pairs)
16
 
17
 
18
+ def alignment_record(text_a, text_b, pairs, fmt="string",
19
+ units_a=None, units_b=None):
20
  """Build one JSONL record: original texts plus the alignment labels.
21
 
22
  ``fmt="string"`` encodes the alignment as a word-alignment-label-notation
23
  string (``"0-0 1-1"``); ``fmt="pairs"`` as a list of ``[i, j]`` pairs.
24
+
25
+ ``units_a`` / ``units_b``, when given, add the strings the label indices
26
+ point at. Whitespace words are recoverable from ``text_a``/``text_b``, so
27
+ these are only emitted for token-level alignment, where the indices refer to
28
+ the encoder's subword tokens and are otherwise uninterpretable.
29
  """
30
  labels = ([list(p) for p in pairs] if fmt == "pairs"
31
  else to_word_alignment_label_notation(pairs))
32
+ record = {"text_a": text_a, "text_b": text_b, "labels": labels}
33
+ if units_a is not None:
34
+ record["units_a"] = list(units_a)
35
+ if units_b is not None:
36
+ record["units_b"] = list(units_b)
37
+ return record
38
 
39
 
40
  def _read_lines(path):
 
50
  granularity=args.granularity,
51
  method=args.method,
52
  k=args.k,
53
+ units=args.units,
54
  device=args.device,
55
  **({"mode": args.mode} if args.mode else {}),
56
  )
 
65
 
66
  out = open(args.output, "w", encoding="utf-8") if args.output else sys.stdout
67
  try:
68
+ token_level = args.units == "tokens"
69
+ results = aligner.align_pairs(zip(src, tgt), show_progress=not args.quiet,
70
+ with_units=token_level)
71
+ for text_a, text_b, result in zip(src, tgt, results):
72
+ pairs, units_a, units_b = result if token_level else (result, None, None)
73
+ record = alignment_record(text_a, text_b, pairs, fmt=args.label_format,
74
+ units_a=units_a, units_b=units_b)
75
  out.write(json.dumps(record, ensure_ascii=False) + "\n")
76
  finally:
77
  if args.output:
 
103
  help="constraint hyperparameter: w blocks (CTFAlign) or k tokens (MDPAlign)")
104
  a.add_argument("--lang-pair", dest="lang_pair",
105
  help="e.g. en-fr, to pick a language-pair-specific tuned layer")
106
+ a.add_argument("--units", choices=list(UNITS), default="words",
107
+ help="what the label indices refer to: 'words' = whitespace-split "
108
+ "words (default; pre-segment zh/ja input), or 'tokens' = the "
109
+ "encoder's subword tokens, with no projection to words. "
110
+ "Token mode also writes 'units_a'/'units_b' to each record")
111
  a.add_argument("--device", help="torch device, e.g. cuda:0 or cpu")
112
  a.add_argument("-o", "--output", help="output JSONL file (default: stdout)")
113
  a.add_argument("--label-format", dest="label_format",
ctfalign/defaults.py CHANGED
@@ -29,7 +29,7 @@ BEST_LAYERS_DOCS = {
29
  # blocks for CTFAlign), used when the user does not pass one.
30
  DEFAULT_K = {
31
  "simalign": None,
32
- "mdpalign-strict": 25, # test default (dev uses 50)
33
  "mdpalign-fuzzy": 150,
34
  "ctfalign": 8,
35
  }
 
29
  # blocks for CTFAlign), used when the user does not pass one.
30
  DEFAULT_K = {
31
  "simalign": None,
32
+ "mdpalign-strict": 25, # modal-best on dev; not reported on test (weakest variant)
33
  "mdpalign-fuzzy": 150,
34
  "ctfalign": 8,
35
  }
ctfalign/encoders/__pycache__/__init__.cpython-311.pyc DELETED
Binary file (667 Bytes)
 
ctfalign/encoders/__pycache__/base.cpython-311.pyc DELETED
Binary file (2.69 kB)
 
ctfalign/encoders/__pycache__/huggingface.cpython-311.pyc DELETED
Binary file (6.24 kB)
 
ctfalign/encoders/base.py CHANGED
@@ -1,8 +1,8 @@
1
  """Encoder interface: the single framework-dependent step.
2
 
3
- An encoder turns text into per-token contextual hidden states at a chosen layer
4
- plus a token-to-word map. Everything downstream (similarity, masking, alignment)
5
- is framework-independent.
6
 
7
  Eligibility rule: an encoder must yield per-token hidden states at a selectable
8
  layer. Pooled-sentence-vector outputs (most embedding APIs) cannot be aligned
@@ -10,7 +10,7 @@ token-to-token and are out of scope.
10
  """
11
  import warnings
12
  from dataclasses import dataclass
13
- from typing import List, Protocol, runtime_checkable
14
 
15
  import torch
16
 
@@ -23,9 +23,14 @@ class EncodedText:
23
  word_ids: length-``n_tokens`` list mapping each token to a whitespace word
24
  index (a "b2w map"). ``len(word_ids)`` must equal
25
  ``embeddings.shape[0]``.
 
 
 
 
26
  """
27
  embeddings: torch.Tensor
28
  word_ids: List[int]
 
29
 
30
  def __post_init__(self):
31
  # Lengths match for normal sequences; long-document chunking can shift
@@ -37,6 +42,12 @@ class EncodedText:
37
  f"({self.embeddings.shape[0]}); extra tokens will be dropped "
38
  f"during word projection."
39
  )
 
 
 
 
 
 
40
 
41
 
42
  @runtime_checkable
 
1
  """Encoder interface: the single framework-dependent step.
2
 
3
+ An encoder turns text into per-token contextual hidden states at a chosen layer,
4
+ a token-to-word map, and (optionally) the token surface strings. Everything
5
+ downstream (similarity, masking, alignment) is framework-independent.
6
 
7
  Eligibility rule: an encoder must yield per-token hidden states at a selectable
8
  layer. Pooled-sentence-vector outputs (most embedding APIs) cannot be aligned
 
10
  """
11
  import warnings
12
  from dataclasses import dataclass
13
+ from typing import List, Optional, Protocol, runtime_checkable
14
 
15
  import torch
16
 
 
23
  word_ids: length-``n_tokens`` list mapping each token to a whitespace word
24
  index (a "b2w map"). ``len(word_ids)`` must equal
25
  ``embeddings.shape[0]``.
26
+ tokens: optional length-``n_tokens`` list of token surface strings. Only
27
+ needed for token-level alignment (``units="tokens"``), where the
28
+ returned indices point into this list rather than into
29
+ whitespace words; ``None`` if the encoder does not provide it.
30
  """
31
  embeddings: torch.Tensor
32
  word_ids: List[int]
33
+ tokens: Optional[List[str]] = None
34
 
35
  def __post_init__(self):
36
  # Lengths match for normal sequences; long-document chunking can shift
 
42
  f"({self.embeddings.shape[0]}); extra tokens will be dropped "
43
  f"during word projection."
44
  )
45
+ if self.tokens is not None and len(self.tokens) != self.embeddings.shape[0]:
46
+ raise ValueError(
47
+ f"tokens length ({len(self.tokens)}) != n_tokens "
48
+ f"({self.embeddings.shape[0]}); token-level alignment indexes "
49
+ f"tokens directly, so a mismatch would mislabel the output."
50
+ )
51
 
52
 
53
  @runtime_checkable
ctfalign/encoders/huggingface.py CHANGED
@@ -1,9 +1,21 @@
1
  """HuggingFace token-level encoder (the batteries-included default).
2
 
3
  Extracts per-token hidden states at a chosen layer, with the same long-sequence
4
- chunking strategy as the research pipeline, and builds the token-to-word map via
5
- character offsets. Uses ``transformers`` (a core dependency of ctfalign).
 
 
 
 
 
 
 
 
 
 
6
  """
 
 
7
  import torch
8
 
9
  from ..wordmap import build_b2w_map
@@ -24,31 +36,75 @@ class HFEncoder:
24
  self.model_name = model_name
25
  self.layer = layer
26
  self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
27
- # Only forward ``token`` when set: older transformers (<4.32) don't accept
28
- # the ``token`` kwarg and leak it into the model __init__ (BertModel/LaBSE
29
- # then raises "unexpected keyword argument 'token'").
30
- auth = {"token": token} if token is not None else {}
31
  self.tokenizer = AutoTokenizer.from_pretrained(
32
- tokenizer_name or model_name, **auth
33
  )
34
  self.model = AutoModel.from_pretrained(
35
- model_name, trust_remote_code=trust_remote_code, **auth
36
  ).to(self.device)
37
  self.model.eval()
38
  self.max_length = self.model.config.max_position_embeddings
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  # -- embedding -----------------------------------------------------------
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  def _embed(self, text):
43
- """Return non-special token embeddings ``(n_tokens, hidden)`` for text."""
 
 
 
 
 
44
  chunk_size = self.max_length - 2
45
- length = len(self.tokenizer.encode(text, add_special_tokens=False))
46
  if length > chunk_size:
 
47
  return self._embed_chunked(text)
48
 
49
  enc = self.tokenizer(
50
  [text], padding=False, truncation=False, return_tensors="pt",
51
- return_special_tokens_mask=True,
52
  ).to(self.device)
53
  enc = dict(enc)
54
  special = enc.pop("special_tokens_mask").bool()
@@ -61,13 +117,18 @@ class HFEncoder:
61
  )
62
  emb = out["hidden_states"][self.layer][0]
63
  keep = enc["attention_mask"].bool()[0] & ~special[0]
64
- return emb[keep]
 
65
 
66
  def _embed_chunked(self, text):
67
- """Embed a long text in non-overlapping context-window-sized chunks."""
 
 
 
68
  chunk_size = self.max_length - 2
69
- full_ids = self.tokenizer.encode(text, add_special_tokens=False)
70
  chunk_embeddings = []
 
71
  for i in range(0, len(full_ids), chunk_size):
72
  chunk_ids = full_ids[i:i + chunk_size]
73
  chunk_text = self.tokenizer.decode(chunk_ids, skip_special_tokens=True)
@@ -82,11 +143,14 @@ class HFEncoder:
82
  emb = out["hidden_states"][self.layer][0]
83
  keep = enc["attention_mask"].bool()[0] & ~special[0]
84
  chunk_embeddings.append(emb[keep])
85
- return torch.cat(chunk_embeddings, dim=0)
 
 
86
 
87
  # -- public API ----------------------------------------------------------
88
 
89
  def encode(self, text: str) -> EncodedText:
90
- embeddings = self._embed(text)
91
  word_ids = build_b2w_map(self.tokenizer, text)
92
- return EncodedText(embeddings=embeddings.cpu(), word_ids=word_ids)
 
 
1
  """HuggingFace token-level encoder (the batteries-included default).
2
 
3
  Extracts per-token hidden states at a chosen layer, with the same long-sequence
4
+ chunking strategy as the research pipeline, builds the token-to-word map via
5
+ character offsets, and returns the token surface strings (used for token-level
6
+ alignment). Uses ``transformers`` (a core dependency of ctfalign).
7
+
8
+ Long-sequence warnings: ``transformers`` emits its own "Token indices sequence
9
+ length is longer ..." message, which claims running the sequence "will result in
10
+ indexing errors" and is keyed off ``tokenizer.model_max_length``. That is
11
+ misleading here -- we deliberately over-tokenise and then chunk, and
12
+ ``model_max_length`` is unset (a ~1e19 sentinel) on some models, e.g. EuroBERT,
13
+ so the message never appears for them however long the document is. We pass
14
+ ``verbose=False`` to silence it and warn ourselves off the model's real context
15
+ window (``config.max_position_embeddings``).
16
  """
17
+ import warnings
18
+
19
  import torch
20
 
21
  from ..wordmap import build_b2w_map
 
36
  self.model_name = model_name
37
  self.layer = layer
38
  self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
 
 
 
 
39
  self.tokenizer = AutoTokenizer.from_pretrained(
40
+ tokenizer_name or model_name, token=token
41
  )
42
  self.model = AutoModel.from_pretrained(
43
+ model_name, token=token, trust_remote_code=trust_remote_code
44
  ).to(self.device)
45
  self.model.eval()
46
  self.max_length = self.model.config.max_position_embeddings
47
+ self._warned_long = False
48
+
49
+ # -- tokens --------------------------------------------------------------
50
+
51
+ def _surface_tokens(self, ids):
52
+ """Human-readable surface string for each token id.
53
+
54
+ ``convert_tokens_to_string`` on a single token resolves the SentencePiece
55
+ and byte-level word-boundary markers (U+2581, U+0120); WordPiece's ``##``
56
+ survives a single-token decode, so it is stripped separately. Falls back
57
+ to the raw token when the decode is empty (e.g. a lone marker).
58
+ """
59
+ tok = self.tokenizer
60
+ surfaces = []
61
+ for t in tok.convert_ids_to_tokens(ids):
62
+ s = tok.convert_tokens_to_string([t]).strip()
63
+ if s.startswith("##"):
64
+ s = s[2:]
65
+ surfaces.append(s or t)
66
+ return surfaces
67
 
68
  # -- embedding -----------------------------------------------------------
69
 
70
+ def _warn_long_sequence(self, length, chunk_size):
71
+ """Warn once per encoder that a text exceeds the model's context window.
72
+
73
+ Reported off ``config.max_position_embeddings`` (e.g. 512 for LaBSE, 8192
74
+ for mmBERT-base and EuroBERT-610m, 32768 / 40960 for Qwen3-Embedding-0.6B
75
+ / -4B) rather than ``tokenizer.model_max_length``, which is unset on some
76
+ models. Warns once per encoder instance so that aligning a corpus of long
77
+ documents does not emit one message per document.
78
+ """
79
+ if self._warned_long:
80
+ return
81
+ self._warned_long = True
82
+ n_chunks = -(-length // chunk_size)
83
+ warnings.warn(
84
+ f"Token sequence length ({length}) exceeds the maximum sequence length "
85
+ f"for {self.model_name} ({self.max_length}); running it through the model "
86
+ f"in one pass may result in indexing errors. Splitting it into {n_chunks} "
87
+ f"chunks of at most {chunk_size} tokens, which are encoded independently: "
88
+ f"no alignment can cross a chunk boundary. Further long sequences will not "
89
+ f"be reported."
90
+ )
91
+
92
  def _embed(self, text):
93
+ """Return ``(embeddings, tokens)`` over the non-special tokens of text.
94
+
95
+ Both come out of the same tokenisation pass, so ``len(tokens)`` always
96
+ equals ``embeddings.shape[0]`` -- unlike ``word_ids``, which is built
97
+ from a separate offset-mapping pass and can drift on chunked documents.
98
+ """
99
  chunk_size = self.max_length - 2
100
+ length = len(self.tokenizer.encode(text, add_special_tokens=False, verbose=False))
101
  if length > chunk_size:
102
+ self._warn_long_sequence(length, chunk_size)
103
  return self._embed_chunked(text)
104
 
105
  enc = self.tokenizer(
106
  [text], padding=False, truncation=False, return_tensors="pt",
107
+ return_special_tokens_mask=True, verbose=False,
108
  ).to(self.device)
109
  enc = dict(enc)
110
  special = enc.pop("special_tokens_mask").bool()
 
117
  )
118
  emb = out["hidden_states"][self.layer][0]
119
  keep = enc["attention_mask"].bool()[0] & ~special[0]
120
+ kept_ids = enc["input_ids"][0][keep].tolist()
121
+ return emb[keep], self._surface_tokens(kept_ids)
122
 
123
  def _embed_chunked(self, text):
124
+ """Embed a long text in non-overlapping context-window-sized chunks.
125
+
126
+ Returns ``(embeddings, tokens)`` concatenated across chunks.
127
+ """
128
  chunk_size = self.max_length - 2
129
+ full_ids = self.tokenizer.encode(text, add_special_tokens=False, verbose=False)
130
  chunk_embeddings = []
131
+ chunk_tokens = []
132
  for i in range(0, len(full_ids), chunk_size):
133
  chunk_ids = full_ids[i:i + chunk_size]
134
  chunk_text = self.tokenizer.decode(chunk_ids, skip_special_tokens=True)
 
143
  emb = out["hidden_states"][self.layer][0]
144
  keep = enc["attention_mask"].bool()[0] & ~special[0]
145
  chunk_embeddings.append(emb[keep])
146
+ kept_ids = enc["input_ids"][0][keep].tolist()
147
+ chunk_tokens.extend(self._surface_tokens(kept_ids))
148
+ return torch.cat(chunk_embeddings, dim=0), chunk_tokens
149
 
150
  # -- public API ----------------------------------------------------------
151
 
152
  def encode(self, text: str) -> EncodedText:
153
+ embeddings, tokens = self._embed(text)
154
  word_ids = build_b2w_map(self.tokenizer, text)
155
+ return EncodedText(embeddings=embeddings.cpu(), word_ids=word_ids,
156
+ tokens=tokens)
ctfalign/masks.py CHANGED
@@ -1,8 +1,10 @@
1
  """Positional masking strategies applied to the similarity matrix.
2
 
3
- - ``add_belt_mask_token_count_fixed_on_longer_side`` -> MDPAlign strict
4
- - ``add_soft_belt_mask_token_count_fixed_on_longer_side`` -> MDPAlign fuzzy
5
- - ``pyramid_hard_lenient2`` -> CTFAlign
 
 
6
 
7
  All belt functions normalise positions so the diagonal spans both corners and
8
  ``token_count`` is interpreted as a tolerance of +/-N tokens on the *longer*
@@ -15,7 +17,7 @@ import torch.nn.functional as F
15
  from .align import argmax_align, iter_max
16
 
17
 
18
- def add_belt_mask_token_count_fixed_on_longer_side(similarity_matrix, token_count):
19
  """Hard diagonal band (MDPAlign strict)."""
20
  m, n = similarity_matrix.shape
21
  i_idx = np.arange(m)[:, None] / m
@@ -25,7 +27,7 @@ def add_belt_mask_token_count_fixed_on_longer_side(similarity_matrix, token_coun
25
  return similarity_matrix * mask
26
 
27
 
28
- def add_soft_belt_mask_token_count_fixed_on_longer_side(similarity_matrix, token_count):
29
  """Soft (Gaussian) diagonal band (MDPAlign fuzzy)."""
30
  m, n = similarity_matrix.shape
31
  i_idx = np.arange(m)[:, None] / m
@@ -36,16 +38,23 @@ def add_soft_belt_mask_token_count_fixed_on_longer_side(similarity_matrix, token
36
  return similarity_matrix * weights
37
 
38
 
39
- def pyramid_hard_lenient2(similarity_matrix, method, width=0):
 
 
 
 
40
  """Coarse-to-fine pyramid masking with lenient recovery (CTFAlign).
41
 
42
- Starts from a 2x2 grid and halves the block size each level. Aligned coarse
43
  blocks (plus a +/-``width`` buffer) are retained; any ``(row, col)`` at the
44
  intersection of an empty block-row and empty block-column is recovered with
45
  the same +/-``width`` buffer. Returns the token-level alignment at the
46
  finest (1x1) level.
47
 
48
  ``method`` is ``"simalign-argmax"`` or ``"simalign-itermax"``.
 
 
 
49
  """
50
  m, n = similarity_matrix.shape
51
  block_h = max(m // 2, 1)
@@ -54,21 +63,32 @@ def pyramid_hard_lenient2(similarity_matrix, method, width=0):
54
  while block_h >= 1 and block_w >= 1:
55
  n_blocks_h = (m + block_h - 1) // block_h
56
  n_blocks_w = (n + block_w - 1) // block_w
 
57
 
58
- coarse = F.avg_pool2d(
59
- similarity_matrix[None, None],
60
- kernel_size=(block_h, block_w),
61
- stride=(block_h, block_w),
62
- ceil_mode=True,
63
- count_include_pad=False,
64
- ).squeeze(0, 1)
 
 
 
 
 
 
 
 
 
65
 
66
  if method == 'simalign-argmax':
67
- coarse_alignment = argmax_align(coarse)
68
  elif method == 'simalign-itermax':
69
- coarse_alignment = iter_max(coarse.cpu().numpy())
 
70
  else:
71
- raise NotImplementedError("Method not implemented for pyramid_hard_lenient2.")
72
 
73
  if block_h == 1 and block_w == 1:
74
  return coarse_alignment
@@ -79,8 +99,6 @@ def pyramid_hard_lenient2(similarity_matrix, method, width=0):
79
  c0 = max(cj - width, 0); c1 = min(cj + width + 1, n_blocks_w)
80
  coarse_mask[r0:r1, c0:c1] = 1.0
81
 
82
- # Lenient recovery: for each (r, c) at the intersection of an empty row
83
- # and an empty column, apply the same +/-width buffer as normal blocks.
84
  empty_rows = coarse_mask.sum(dim=1) == 0
85
  empty_cols = coarse_mask.sum(dim=0) == 0
86
  for ci, cj in (empty_rows[:, None] & empty_cols[None, :]).nonzero(as_tuple=False).tolist():
@@ -88,12 +106,17 @@ def pyramid_hard_lenient2(similarity_matrix, method, width=0):
88
  c0 = max(cj - width, 0); c1 = min(cj + width + 1, n_blocks_w)
89
  coarse_mask[r0:r1, c0:c1] = 1.0
90
 
91
- mask = F.interpolate(
92
- coarse_mask[None, None],
93
- size=(n_blocks_h * block_h, n_blocks_w * block_w),
94
- mode='nearest'
95
- ).squeeze(0, 1)[:m, :n]
96
- similarity_matrix = similarity_matrix * mask
 
 
 
 
 
97
 
98
  block_h = max(block_h // 2, 1)
99
  block_w = max(block_w // 2, 1)
 
1
  """Positional masking strategies applied to the similarity matrix.
2
 
3
+ - ``apply_mdpalign_strict`` -> MDPAlign strict
4
+ - ``apply_mdpalign_fuzzy`` -> MDPAlign fuzzy
5
+ - ``ctfalign`` -> CTFAlign
6
+
7
+ Names match the paper and the research pipeline's ``get_predictions.py``.
8
 
9
  All belt functions normalise positions so the diagonal spans both corners and
10
  ``token_count`` is interpreted as a tolerance of +/-N tokens on the *longer*
 
17
  from .align import argmax_align, iter_max
18
 
19
 
20
+ def apply_mdpalign_strict(similarity_matrix, token_count):
21
  """Hard diagonal band (MDPAlign strict)."""
22
  m, n = similarity_matrix.shape
23
  i_idx = np.arange(m)[:, None] / m
 
27
  return similarity_matrix * mask
28
 
29
 
30
+ def apply_mdpalign_fuzzy(similarity_matrix, token_count):
31
  """Soft (Gaussian) diagonal band (MDPAlign fuzzy)."""
32
  m, n = similarity_matrix.shape
33
  i_idx = np.arange(m)[:, None] / m
 
38
  return similarity_matrix * weights
39
 
40
 
41
+ def _level_is_inert(n_blocks_h, n_blocks_w, width):
42
+ return width >= max(n_blocks_h, n_blocks_w) - 1
43
+
44
+
45
+ def ctfalign(similarity_matrix, method, width=0, drop_negative=True):
46
  """Coarse-to-fine pyramid masking with lenient recovery (CTFAlign).
47
 
48
+ Starts from a ~2x2 grid and halves the block size each level. Aligned coarse
49
  blocks (plus a +/-``width`` buffer) are retained; any ``(row, col)`` at the
50
  intersection of an empty block-row and empty block-column is recovered with
51
  the same +/-``width`` buffer. Returns the token-level alignment at the
52
  finest (1x1) level.
53
 
54
  ``method`` is ``"simalign-argmax"`` or ``"simalign-itermax"``.
55
+ ``drop_negative`` discards pairs whose similarity is not positive.
56
+
57
+ Levels whose mask cannot remove anything are skipped; see ``_level_is_inert``.
58
  """
59
  m, n = similarity_matrix.shape
60
  block_h = max(m // 2, 1)
 
63
  while block_h >= 1 and block_w >= 1:
64
  n_blocks_h = (m + block_h - 1) // block_h
65
  n_blocks_w = (n + block_w - 1) // block_w
66
+ final_level = block_h == 1 and block_w == 1
67
 
68
+ # Skip levels that cannot constrain anything due to the buffer/grid size:
69
+ if not final_level and _level_is_inert(n_blocks_h, n_blocks_w, width):
70
+ block_h = max(block_h // 2, 1)
71
+ block_w = max(block_w // 2, 1)
72
+ continue
73
+
74
+ if block_h == 1 and block_w == 1:
75
+ coarse = similarity_matrix
76
+ else:
77
+ coarse = F.avg_pool2d(
78
+ similarity_matrix[None, None].clamp(min=0),
79
+ kernel_size=(block_h, block_w),
80
+ stride=(block_h, block_w),
81
+ ceil_mode=True,
82
+ count_include_pad=False,
83
+ ).squeeze(0, 1)
84
 
85
  if method == 'simalign-argmax':
86
+ coarse_alignment = argmax_align(coarse, drop_negative=drop_negative)
87
  elif method == 'simalign-itermax':
88
+ coarse_alignment = iter_max(coarse.cpu().numpy(),
89
+ drop_negative=drop_negative)
90
  else:
91
+ raise NotImplementedError("Method not implemented for ctfalign.")
92
 
93
  if block_h == 1 and block_w == 1:
94
  return coarse_alignment
 
99
  c0 = max(cj - width, 0); c1 = min(cj + width + 1, n_blocks_w)
100
  coarse_mask[r0:r1, c0:c1] = 1.0
101
 
 
 
102
  empty_rows = coarse_mask.sum(dim=1) == 0
103
  empty_cols = coarse_mask.sum(dim=0) == 0
104
  for ci, cj in (empty_rows[:, None] & empty_cols[None, :]).nonzero(as_tuple=False).tolist():
 
106
  c0 = max(cj - width, 0); c1 = min(cj + width + 1, n_blocks_w)
107
  coarse_mask[r0:r1, c0:c1] = 1.0
108
 
109
+ # An all-ones mask is an identity multiply. ``_level_is_inert`` catches
110
+ # the cases predictable from the grid size alone; this catches the rest,
111
+ # where the aligned blocks happen to spread far enough that their
112
+ # buffers cover the grid -- only knowable once they are computed.
113
+ if not bool(coarse_mask.all()):
114
+ mask = F.interpolate(
115
+ coarse_mask[None, None],
116
+ size=(n_blocks_h * block_h, n_blocks_w * block_w),
117
+ mode='nearest'
118
+ ).squeeze(0, 1)[:m, :n]
119
+ similarity_matrix = similarity_matrix * mask
120
 
121
  block_h = max(block_h // 2, 1)
122
  block_w = max(block_w // 2, 1)
ctfalign/wordmap.py CHANGED
@@ -58,6 +58,7 @@ def build_b2w_map(tokenizer, sentence: str) -> list:
58
  return_special_tokens_mask=True,
59
  add_special_tokens=True,
60
  truncation=False,
 
61
  )
62
 
63
  offset_mapping = encoding["offset_mapping"]
 
58
  return_special_tokens_mask=True,
59
  add_special_tokens=True,
60
  truncation=False,
61
+ verbose=False, # long docs are chunked downstream; see encoders/huggingface.py
62
  )
63
 
64
  offset_mapping = encoding["offset_mapping"]
requirements.txt CHANGED
@@ -1,6 +1,6 @@
1
  # The ctfalign package is vendored into this Space (see ./ctfalign), so we list
2
  # its runtime dependencies directly rather than installing from GitHub.
3
- # Source of truth: https://github.com/miwytt/doc-wordalign (re-copy src/ctfalign on changes)
4
  numpy
5
  # >=2.6: recent transformers refuses to torch.load .bin checkpoints (mmBERT ships
6
  # only pytorch_model.bin) on older torch (CVE-2025-32434).
 
1
  # The ctfalign package is vendored into this Space (see ./ctfalign), so we list
2
  # its runtime dependencies directly rather than installing from GitHub.
3
+ # Source of truth: https://github.com/ZurichNLP/CTFAlign (re-copy src/ctfalign on changes)
4
  numpy
5
  # >=2.6: recent transformers refuses to torch.load .bin checkpoints (mmBERT ships
6
  # only pytorch_model.bin) on older torch (CVE-2025-32434).