Spaces:
Runtime error
Runtime error
Commit Β·
a9f02dd
1
Parent(s): 2f1f9f7
Stabilize classifier logits for inference
Browse files- scripts/tmos_classifier.py +11 -3
scripts/tmos_classifier.py
CHANGED
|
@@ -72,8 +72,8 @@ class TMOSClassifier(nn.Module):
|
|
| 72 |
for param in self.base.lm_head.parameters():
|
| 73 |
param.requires_grad = False
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
self.classifier = nn.Linear(hidden_size, 1, dtype=
|
| 77 |
nn.init.xavier_uniform_(self.classifier.weight)
|
| 78 |
nn.init.zeros_(self.classifier.bias)
|
| 79 |
|
|
@@ -122,8 +122,16 @@ class TMOSClassifier(nn.Module):
|
|
| 122 |
# No mask β just take the last position
|
| 123 |
pooled = last_hidden_state[:, -1, :]
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
# ββ 3. Classify ββ
|
| 126 |
-
logit = self.classifier(pooled) # (B, 1)
|
|
|
|
| 127 |
|
| 128 |
result = {"logit": logit}
|
| 129 |
|
|
|
|
| 72 |
for param in self.base.lm_head.parameters():
|
| 73 |
param.requires_grad = False
|
| 74 |
|
| 75 |
+
# Keep the classifier head in fp32 for numerical stability.
|
| 76 |
+
self.classifier = nn.Linear(hidden_size, 1, dtype=torch.float32)
|
| 77 |
nn.init.xavier_uniform_(self.classifier.weight)
|
| 78 |
nn.init.zeros_(self.classifier.bias)
|
| 79 |
|
|
|
|
| 122 |
# No mask β just take the last position
|
| 123 |
pooled = last_hidden_state[:, -1, :]
|
| 124 |
|
| 125 |
+
# Replace non-finite activations defensively before the classifier.
|
| 126 |
+
pooled = torch.nan_to_num(pooled, nan=0.0, posinf=1e4, neginf=-1e4)
|
| 127 |
+
|
| 128 |
+
# Match classifier device to pooled features when model is sharded/offloaded.
|
| 129 |
+
if self.classifier.weight.device != pooled.device:
|
| 130 |
+
self.classifier = self.classifier.to(pooled.device)
|
| 131 |
+
|
| 132 |
# ββ 3. Classify ββ
|
| 133 |
+
logit = self.classifier(pooled.float()) # (B, 1)
|
| 134 |
+
logit = torch.nan_to_num(logit, nan=0.0, posinf=20.0, neginf=-20.0)
|
| 135 |
|
| 136 |
result = {"logit": logit}
|
| 137 |
|