meryyllebr543 commited on
Commit
d599e08
·
verified ·
1 Parent(s): 0a0303c

Upload modeling_lunaris_guard.py

Browse files
Files changed (1) hide show
  1. modeling_lunaris_guard.py +76 -0
modeling_lunaris_guard.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LunarisGuardModel — Hub-loadable version.
3
+
4
+ This module is what gets loaded when a user runs:
5
+
6
+ AutoModel.from_pretrained("auren-research/lunaris-guard", trust_remote_code=True)
7
+
8
+ The class is the same dual-head classifier used in training, but configured
9
+ to load weights from a HF Hub repo via PretrainedConfig + auto_map.
10
+
11
+ Returns a dict with keys:
12
+ - injection_logits: [B, 2]
13
+ - safety_logits: [B, 2]
14
+ - pooled_output: [B, hidden_size] (debug / probing)
15
+ """
16
+
17
+ from typing import Optional
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from transformers import AutoModel, PreTrainedModel
22
+
23
+ from .configuration_lunaris_guard import LunarisGuardConfig
24
+
25
+
26
+ class LunarisGuardModel(PreTrainedModel):
27
+ """Dual-head classifier: injection + content safety, on a ModernBERT backbone."""
28
+
29
+ config_class = LunarisGuardConfig
30
+ base_model_prefix = "backbone"
31
+ supports_gradient_checkpointing = True
32
+
33
+ def __init__(self, config: LunarisGuardConfig):
34
+ super().__init__(config)
35
+ self.config = config
36
+
37
+ # Backbone: ModernBERT-base. Loaded fresh; the saved state_dict will
38
+ # overwrite these weights when from_pretrained() runs.
39
+ self.backbone = AutoModel.from_pretrained(
40
+ config.base_model_name, trust_remote_code=True,
41
+ )
42
+
43
+ self.dropout = nn.Dropout(config.classifier_dropout)
44
+
45
+ self.injection_head = nn.Linear(
46
+ config.hidden_size, config.num_injection_classes
47
+ )
48
+ self.safety_head = nn.Linear(
49
+ config.hidden_size, config.num_safety_classes
50
+ )
51
+
52
+ def forward(
53
+ self,
54
+ input_ids: torch.Tensor,
55
+ attention_mask: Optional[torch.Tensor] = None,
56
+ injection_labels: Optional[torch.Tensor] = None,
57
+ safety_labels: Optional[torch.Tensor] = None,
58
+ **kwargs,
59
+ ):
60
+ outputs = self.backbone(
61
+ input_ids=input_ids,
62
+ attention_mask=attention_mask,
63
+ return_dict=True,
64
+ )
65
+ # CLS pooling
66
+ pooled = outputs.last_hidden_state[:, 0, :]
67
+ pooled = self.dropout(pooled)
68
+
69
+ injection_logits = self.injection_head(pooled)
70
+ safety_logits = self.safety_head(pooled)
71
+
72
+ return {
73
+ "injection_logits": injection_logits,
74
+ "safety_logits": safety_logits,
75
+ "pooled_output": pooled,
76
+ }