handwoven8588 commited on
Commit
4c04d49
·
verified ·
1 Parent(s): 8187d6a

Auto mode probes the varlen kernel and falls back; eager accepts a 2-D mask

Browse files
Files changed (2) hide show
  1. README.md +11 -6
  2. modeling_hf_nomic_bert.py +79 -14
README.md CHANGED
@@ -51,10 +51,13 @@ file ships all three paths itself, so no runtime patching or post-load hooks are
51
  3. **`eager`** — everything else: CPU, pre-Ampere GPUs, or neither of the above available. The
52
  original padded attention algorithm, unchanged, runs on any host.
53
 
54
- `auto` (the default) prefers `torch_varlen`, then `flash_attn`, then `eager`. A forced override
55
- (e.g. `NOMIC_BERT_ATTN_IMPL=torch_varlen`) **raises** `RuntimeError` if that tier's precondition
56
- doesn't hold — a forced tier never falls back silently. An unrecognized override raises
57
- `ValueError`.
 
 
 
58
  - **See which tier engaged**: `model[0].auto_model.attention_impl` after a forward pass, or the
59
  one-time `NomicBert attention impl=... device=... capability=... torch=... flash_attn=...
60
  override=...` INFO log line (one line per distinct `(impl, device)`).
@@ -130,8 +133,10 @@ at batch size 256.
130
  attention implementations at call time — `torch_varlen` (torch's own
131
  `torch.nn.attention.varlen.varlen_attn`, no third-party kernel, needs torch ≥ 2.10.0),
132
  `flash_attn` (the original flash-attn varlen-packed kernel, kept as a fallback for older torch
133
- builds that have it installed), and `eager` (the original padded attention, unchanged, and the
134
- default off CUDA sm_80+). Both varlen tiers unpad the input with torch-native `_unpad`/`_pad`
 
 
135
  helpers (a replacement for `flash_attn.bert_padding`) before the packed kernel call, then repad
136
  the output; `NomicBertModel.forward` builds the additive attention mask inline instead of calling
137
  the (now-removed-upstream) `get_extended_attention_mask` helper. Rotary embeddings are applied to
 
51
  3. **`eager`** — everything else: CPU, pre-Ampere GPUs, or neither of the above available. The
52
  original padded attention algorithm, unchanged, runs on any host.
53
 
54
+ `auto` (the default) prefers `torch_varlen`, then `flash_attn`, then `eager`. Before accepting a
55
+ varlen tier, `auto` runs one tiny kernel probe per device (a capability check alone can't tell
56
+ whether the installed build has a kernel for the GPU's architecture, e.g. on ROCm); if the probe
57
+ raises, it logs one WARNING naming the tier and the error and steps down to the next tier. A
58
+ forced override (e.g. `NOMIC_BERT_ATTN_IMPL=torch_varlen`) is not probed and **raises**
59
+ `RuntimeError` if that tier's precondition doesn't hold — a forced tier never falls back
60
+ silently. An unrecognized override raises `ValueError`.
61
  - **See which tier engaged**: `model[0].auto_model.attention_impl` after a forward pass, or the
62
  one-time `NomicBert attention impl=... device=... capability=... torch=... flash_attn=...
63
  override=...` INFO log line (one line per distinct `(impl, device)`).
 
133
  attention implementations at call time — `torch_varlen` (torch's own
134
  `torch.nn.attention.varlen.varlen_attn`, no third-party kernel, needs torch ≥ 2.10.0),
135
  `flash_attn` (the original flash-attn varlen-packed kernel, kept as a fallback for older torch
136
+ builds that have it installed), and `eager` (the original padded attention algorithm, numerically
137
+ unchanged, and the default off CUDA sm_80+; it now converts a raw 2-D `[B, S]` mask to the
138
+ additive form before adding it, for the case where a `device_map` split hands it a mask a varlen
139
+ tier upstream never passes). Both varlen tiers unpad the input with torch-native `_unpad`/`_pad`
140
  helpers (a replacement for `flash_attn.bert_padding`) before the packed kernel call, then repad
141
  the output; `NomicBertModel.forward` builds the additive attention mask inline instead of calling
142
  the (now-removed-upstream) `get_extended_attention_mask` helper. Rotary embeddings are applied to
modeling_hf_nomic_bert.py CHANGED
@@ -36,8 +36,10 @@ from .configuration_hf_nomic_bert import NomicBertConfig
36
  # 3. eager — the original padded path, byte-for-byte, runs everywhere
37
  # Both tier 1 and tier 2 run the same FA2-family kernel and refuse pre-Ampere
38
  # hardware, so a single capability predicate gates both (resolve_attention_impl,
39
- # below). When neither is available (CPU-only hosts, or builds without them)
40
- # tier 3 runs unchanged, so this model loads and encodes everywhere.
 
 
41
  try: # pragma: no cover - import guard, exercised by environment
42
  from torch.nn.attention.varlen import varlen_attn as _torch_varlen_attn
43
 
@@ -100,17 +102,76 @@ def resolve_attention_impl(
100
  return override
101
 
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  @functools.lru_cache(maxsize=None)
104
  def _select_cached(dev_type, dev_index, override):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  is_cuda = dev_type == "cuda"
106
- cap = torch.cuda.get_device_capability(torch.device(dev_type, dev_index)) if is_cuda else None
107
- return resolve_attention_impl(
108
- override=override,
109
- torch_varlen_available=_TORCH_VARLEN_AVAILABLE,
110
- flash_available=_FLASH_AVAILABLE,
111
- is_cuda=is_cuda,
112
- capability=cap,
113
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
 
116
  def _unpad(x: torch.Tensor, mask: torch.Tensor):
@@ -151,9 +212,6 @@ def select_attention_impl(device: torch.device) -> str:
151
  return _select_cached(device.type, device.index, override)
152
 
153
 
154
- logger = logging.getLogger(__name__)
155
-
156
-
157
  def _inline_extended_mask(attention_mask: Optional[torch.Tensor], dtype: torch.dtype) -> Optional[torch.Tensor]:
158
  """Build the additive ``[B, 1, 1, S]`` mask the eager tier consumes.
159
 
@@ -1021,7 +1079,8 @@ class NomicBertAttention(nn.Module):
1021
  return self.out_proj(attn_output)
1022
 
1023
  # --- Eager path (no varlen tier engaged: CPU, pre-Ampere, forced, or no kernel) ---
1024
- # Byte-for-byte identical to nomic-ai/CodeRankEmbed upstream.
 
1025
  query, key, value = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
1026
 
1027
  query = query.permute(0, 2, 1, 3)
@@ -1030,6 +1089,12 @@ class NomicBertAttention(nn.Module):
1030
 
1031
  attention_scores = torch.matmul(query, key.transpose(-1, -2)) / self.norm_factor
1032
  if attention_mask is not None:
 
 
 
 
 
 
1033
  attention_scores = attention_scores + attention_mask
1034
 
1035
  attentions_probs = F.softmax(attention_scores, dim=-1)
 
36
  # 3. eager — the original padded path, byte-for-byte, runs everywhere
37
  # Both tier 1 and tier 2 run the same FA2-family kernel and refuse pre-Ampere
38
  # hardware, so a single capability predicate gates both (resolve_attention_impl,
39
+ # below). In auto mode a tiny kernel probe then confirms the chosen varlen tier
40
+ # actually runs on the device, stepping down a tier if it raises (_select_cached).
41
+ # When neither is available (CPU-only hosts, or builds without them) tier 3 runs
42
+ # unchanged, so this model loads and encodes everywhere.
43
  try: # pragma: no cover - import guard, exercised by environment
44
  from torch.nn.attention.varlen import varlen_attn as _torch_varlen_attn
45
 
 
102
  return override
103
 
104
 
105
+ logger = logging.getLogger(__name__)
106
+
107
+
108
+ def _probe_varlen_kernel(impl: str, device: torch.device) -> None:
109
+ """Run one tiny forward through ``impl``'s kernel on ``device``; raise on failure.
110
+
111
+ bf16 q/k/v with two tokens, one head, head_dim 64 and one sequence
112
+ (``cu_seqlens = [0, 2]``), called with the same convention as
113
+ ``NomicBertAttention.forward``. It exists because the capability predicate is
114
+ only a proxy: a torch build can ship ``torch.nn.attention.varlen`` without an
115
+ FA kernel for the device's arch, and on ROCm ``device.type`` is ``"cuda"`` and
116
+ the capability is the gfx major.
117
+ """
118
+ qkv = torch.randn(2, 3, 1, 64, device=device, dtype=torch.bfloat16)
119
+ cu = torch.tensor([0, 2], device=device, dtype=torch.int32)
120
+ if impl == "torch_varlen":
121
+ q, k, v = qkv.unbind(1)
122
+ _torch_varlen_attn(q, k, v, cu, cu, 2, 2)
123
+ else:
124
+ flash_attn_varlen_qkvpacked_func(qkv, cu, 2, dropout_p=0.0, causal=False)
125
+ torch.cuda.synchronize(device)
126
+
127
+
128
  @functools.lru_cache(maxsize=None)
129
  def _select_cached(dev_type, dev_index, override):
130
+ """Resolve the tier for one device, probing the kernel in auto mode.
131
+
132
+ A forced tier is returned exactly as ``resolve_attention_impl`` decides it (or
133
+ raises), with no probe: it never falls back. In ``auto`` mode a varlen tier is
134
+ accepted only if ``_probe_varlen_kernel`` runs; if the probe raises, one
135
+ WARNING names the rejected tier and the exception, that tier is marked
136
+ unavailable, and the pure selector picks again (``torch_varlen`` ->
137
+ ``flash_attn`` -> ``eager``). The probe is the single authority on whether a
138
+ varlen kernel runs, on every backend: ROCm gets no separate predicate, it is
139
+ probed like CUDA. The result, including a fallback, is memoized per
140
+ ``(device, override)``, so the probe runs once per device per process. A
141
+ ``torch.cuda.OutOfMemoryError`` from the probe is re-raised immediately
142
+ instead, with no WARNING and no tier marked unavailable; ``lru_cache`` never
143
+ memoizes a raised call, so a transient OOM never permanently pins the device
144
+ to a lower tier.
145
+ """
146
  is_cuda = dev_type == "cuda"
147
+ device = torch.device(dev_type, dev_index)
148
+ cap = torch.cuda.get_device_capability(device) if is_cuda else None
149
+ available = {"torch_varlen": _TORCH_VARLEN_AVAILABLE, "flash_attn": _FLASH_AVAILABLE}
150
+ while True:
151
+ impl = resolve_attention_impl(
152
+ override=override,
153
+ torch_varlen_available=available["torch_varlen"],
154
+ flash_available=available["flash_attn"],
155
+ is_cuda=is_cuda,
156
+ capability=cap,
157
+ )
158
+ if override != "auto" or impl == "eager":
159
+ return impl
160
+ try:
161
+ _probe_varlen_kernel(impl, device)
162
+ return impl
163
+ except torch.cuda.OutOfMemoryError:
164
+ raise
165
+ except Exception as exc:
166
+ logger.warning(
167
+ "NomicBert attention: auto rejected impl=%s on device=%s (probe raised %s: %s); "
168
+ "trying the next tier",
169
+ impl,
170
+ device,
171
+ type(exc).__name__,
172
+ exc,
173
+ )
174
+ available[impl] = False
175
 
176
 
177
  def _unpad(x: torch.Tensor, mask: torch.Tensor):
 
212
  return _select_cached(device.type, device.index, override)
213
 
214
 
 
 
 
215
  def _inline_extended_mask(attention_mask: Optional[torch.Tensor], dtype: torch.dtype) -> Optional[torch.Tensor]:
216
  """Build the additive ``[B, 1, 1, S]`` mask the eager tier consumes.
217
 
 
1079
  return self.out_proj(attn_output)
1080
 
1081
  # --- Eager path (no varlen tier engaged: CPU, pre-Ampere, forced, or no kernel) ---
1082
+ # Numerically identical to nomic-ai/CodeRankEmbed upstream; the 2-D mask guard
1083
+ # below only fires on a mask upstream never passes.
1084
  query, key, value = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
1085
 
1086
  query = query.permute(0, 2, 1, 3)
 
1089
 
1090
  attention_scores = torch.matmul(query, key.transpose(-1, -2)) / self.norm_factor
1091
  if attention_mask is not None:
1092
+ if attention_mask.ndim == 2:
1093
+ # A raw {0,1} [B, S] mask reached the eager tier: the model-level
1094
+ # decision picked a varlen tier on another device (device_map
1095
+ # sharding layers across GPUs of different capability). Make it
1096
+ # additive here; adding it raw would leave padding keys unmasked.
1097
+ attention_mask = _inline_extended_mask(attention_mask, attention_scores.dtype)
1098
  attention_scores = attention_scores + attention_mask
1099
 
1100
  attentions_probs = F.softmax(attention_scores, dim=-1)