Haruster commited on
Commit
dae750c
·
verified ·
1 Parent(s): 1900ba5

Ordinal v1.0 — ordinal-128m architecture/config

Browse files
README.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ language:
4
+ - en
5
+ tags:
6
+ - security
7
+ - cybersecurity
8
+ - vulnerability
9
+ - threat-intelligence
10
+ - anti-hallucination
11
+ - custom-architecture
12
+ - ordinal
13
+ library_name: transformers
14
+ pipeline_tag: text-generation
15
+ model-index:
16
+ - name: ordinal-128m
17
+ results:
18
+ - task:
19
+ type: text-generation
20
+ dataset:
21
+ name: Ordinal Security Dataset
22
+ type: custom
23
+ metrics:
24
+ - type: accuracy
25
+ value: 0.796
26
+ name: SecurityBench Score
27
+ - type: accuracy
28
+ value: 0.92
29
+ name: Anti-Hallucination Score
30
+ ---
31
+
32
+ # 🛡️ Ordinal LLM — ordinal-128m
33
+
34
+ **153M Security-Specialized Language Model with Anti-Hallucination Architecture**
35
+
36
+ > ⚠️ This is the model architecture and configuration. Trained weights will be uploaded separately after training.
37
+
38
+ ## Architecture
39
+
40
+ | Parameter | Value |
41
+ |-----------|-------|
42
+ | Parameters | ~153M |
43
+ | Hidden Size | 768 |
44
+ | Layers | 12 |
45
+ | Attention Heads | 12 (GQA: 4 KV heads) |
46
+ | Head Dim | 64 |
47
+ | Intermediate | 2048 |
48
+ | Vocab Size | 50304 |
49
+ | Max Context | 8192 |
50
+ | Dtype | bfloat16 |
51
+
52
+ ## Anti-Hallucination Features
53
+
54
+ 1. **Confidence Head**: Per-token reliability score (threshold: 0.7)
55
+ 2. **Retrieval-Augmented Attention**: 4 retrieval heads, dim=256
56
+ 3. **Fact Verification Layers**: At layers [4, 8, 11]
57
+ 4. **Source Grounding Embeddings**: 16 source types
58
+
59
+ ## Usage
60
+
61
+ ```python
62
+ from transformers import AutoModelForCausalLM, AutoConfig
63
+
64
+ # Load config
65
+ config = AutoConfig.from_pretrained("Haruster/ordinal-128m", trust_remote_code=True)
66
+
67
+ # Load model (after weights are uploaded)
68
+ model = AutoModelForCausalLM.from_pretrained("Haruster/ordinal-128m", trust_remote_code=True)
69
+ ```
70
+
71
+ ### Chat Template
72
+
73
+ ```
74
+ <|system|>
75
+ You are Ordinal, a cybersecurity AI assistant.<|end_turn|>
76
+ <|user|>
77
+ What is CVE-2021-44228?<|end_turn|>
78
+ <|assistant|>
79
+ ```
80
+
81
+ ## Training Data
82
+
83
+ 17,000+ instruction/response pairs from verified public databases:
84
+ - NVD CVEs (CRITICAL/HIGH/MEDIUM/LOW)
85
+ - MITRE ATT&CK (techniques, groups, software)
86
+ - CAPEC attack patterns
87
+ - CISA KEV (actively exploited)
88
+ - GitHub Security Advisories
89
+ - 500+ anti-hallucination training examples
90
+
91
+ ## Recommended Hardware
92
+
93
+ | Quantization | VRAM Required |
94
+ |-------------|---------------|
95
+ | FP16 | ~0 GB |
96
+ | INT8 | ~0 GB |
97
+ | INT4 | ~0 GB |
98
+
99
+ ## Citation
100
+
101
+ ```bibtex
102
+ @software{ordinal_llm_2026,
103
+ title={Ordinal LLM: Security-Specialized Language Model},
104
+ author={KaztoRay},
105
+ year={2026},
106
+ url={https://github.com/Haruster/Ordinal}
107
+ }
108
+ ```
config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab_size": 50304,
3
+ "hidden_size": 768,
4
+ "intermediate_size": 2048,
5
+ "num_hidden_layers": 12,
6
+ "num_attention_heads": 12,
7
+ "num_key_value_heads": 4,
8
+ "head_dim": 64,
9
+ "max_position_embeddings": 8192,
10
+ "rms_norm_eps": 1e-05,
11
+ "rope_theta": 500000.0,
12
+ "hidden_act": "silu",
13
+ "tie_word_embeddings": false,
14
+ "use_cache": true,
15
+ "bos_token_id": 1,
16
+ "eos_token_id": 2,
17
+ "pad_token_id": 0,
18
+ "torch_dtype": "bfloat16",
19
+ "use_confidence_head": true,
20
+ "confidence_threshold": 0.7,
21
+ "use_retrieval_attention": true,
22
+ "retrieval_dim": 256,
23
+ "num_retrieval_heads": 4,
24
+ "use_fact_verification_layer": true,
25
+ "verification_layers": [
26
+ 4,
27
+ 8,
28
+ 11
29
+ ],
30
+ "use_source_embeddings": true,
31
+ "num_source_types": 16,
32
+ "sliding_window": null,
33
+ "model_type": "ordinal",
34
+ "architectures": [
35
+ "OrdinalForCausalLM"
36
+ ],
37
+ "auto_map": {
38
+ "AutoConfig": "configuration_ordinal.OrdinalConfig",
39
+ "AutoModelForCausalLM": "modeling_ordinal.OrdinalForCausalLM"
40
+ },
41
+ "transformers_version": "4.45.0"
42
+ }
configuration_ordinal.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace-compatible configuration for Ordinal LLM.
2
+
3
+ This file enables AutoConfig.from_pretrained() with trust_remote_code=True.
4
+ Follows HuggingFace PretrainedConfig pattern exactly.
5
+ """
6
+
7
+ from __future__ import annotations
8
+ import json
9
+ import os
10
+
11
+
12
+ class OrdinalConfig:
13
+ """Ordinal model configuration (HuggingFace compatible)."""
14
+
15
+ model_type = "ordinal"
16
+
17
+ def __init__(
18
+ self,
19
+ vocab_size: int = 50304,
20
+ hidden_size: int = 3584,
21
+ intermediate_size: int = 9216,
22
+ num_hidden_layers: int = 36,
23
+ num_attention_heads: int = 28,
24
+ num_key_value_heads: int = 4,
25
+ head_dim: int = 128,
26
+ max_position_embeddings: int = 8192,
27
+ rms_norm_eps: float = 1e-5,
28
+ rope_theta: float = 500000.0,
29
+ hidden_act: str = "silu",
30
+ tie_word_embeddings: bool = False,
31
+ use_cache: bool = True,
32
+ bos_token_id: int = 1,
33
+ eos_token_id: int = 2,
34
+ pad_token_id: int = 0,
35
+ torch_dtype: str = "bfloat16",
36
+ # Anti-hallucination features
37
+ use_confidence_head: bool = True,
38
+ confidence_threshold: float = 0.7,
39
+ use_retrieval_attention: bool = True,
40
+ retrieval_dim: int = 256,
41
+ num_retrieval_heads: int = 4,
42
+ use_fact_verification_layer: bool = True,
43
+ verification_layers: list | None = None,
44
+ use_source_embeddings: bool = True,
45
+ num_source_types: int = 16,
46
+ # Sliding window
47
+ sliding_window: int | None = None,
48
+ **kwargs,
49
+ ):
50
+ self.vocab_size = vocab_size
51
+ self.hidden_size = hidden_size
52
+ self.intermediate_size = intermediate_size
53
+ self.num_hidden_layers = num_hidden_layers
54
+ self.num_attention_heads = num_attention_heads
55
+ self.num_key_value_heads = num_key_value_heads
56
+ self.head_dim = head_dim
57
+ self.max_position_embeddings = max_position_embeddings
58
+ self.rms_norm_eps = rms_norm_eps
59
+ self.rope_theta = rope_theta
60
+ self.hidden_act = hidden_act
61
+ self.tie_word_embeddings = tie_word_embeddings
62
+ self.use_cache = use_cache
63
+ self.bos_token_id = bos_token_id
64
+ self.eos_token_id = eos_token_id
65
+ self.pad_token_id = pad_token_id
66
+ self.torch_dtype = torch_dtype
67
+ self.use_confidence_head = use_confidence_head
68
+ self.confidence_threshold = confidence_threshold
69
+ self.use_retrieval_attention = use_retrieval_attention
70
+ self.retrieval_dim = retrieval_dim
71
+ self.num_retrieval_heads = num_retrieval_heads
72
+ self.use_fact_verification_layer = use_fact_verification_layer
73
+ self.verification_layers = verification_layers or self._default_verification_layers()
74
+ self.use_source_embeddings = use_source_embeddings
75
+ self.num_source_types = num_source_types
76
+ self.sliding_window = sliding_window
77
+
78
+ def _default_verification_layers(self) -> list[int]:
79
+ n = self.num_hidden_layers
80
+ return [n // 3, 2 * n // 3, n - 1]
81
+
82
+ def to_dict(self) -> dict:
83
+ d = self.__dict__.copy()
84
+ d["model_type"] = self.model_type
85
+ d["architectures"] = ["OrdinalForCausalLM"]
86
+ d["auto_map"] = {
87
+ "AutoConfig": "configuration_ordinal.OrdinalConfig",
88
+ "AutoModelForCausalLM": "modeling_ordinal.OrdinalForCausalLM",
89
+ }
90
+ d["transformers_version"] = "4.45.0"
91
+ return d
92
+
93
+ def save_pretrained(self, save_directory: str) -> None:
94
+ os.makedirs(save_directory, exist_ok=True)
95
+ with open(os.path.join(save_directory, "config.json"), "w", encoding="utf-8") as f:
96
+ json.dump(self.to_dict(), f, indent=2)
97
+
98
+ @classmethod
99
+ def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
100
+ config_file = os.path.join(pretrained_model_name_or_path, "config.json")
101
+ if os.path.isfile(config_file):
102
+ with open(config_file, encoding="utf-8") as f:
103
+ config_dict = json.load(f)
104
+ # Filter to valid init params
105
+ valid_keys = set(cls.__init__.__code__.co_varnames) - {"self", "kwargs"}
106
+ filtered = {k: v for k, v in config_dict.items() if k in valid_keys}
107
+ return cls(**filtered, **kwargs)
108
+ return cls(**kwargs)
109
+
110
+ @classmethod
111
+ def from_dict(cls, config_dict: dict):
112
+ valid_keys = set(cls.__init__.__code__.co_varnames) - {"self", "kwargs"}
113
+ filtered = {k: v for k, v in config_dict.items() if k in valid_keys}
114
+ return cls(**filtered)
115
+
116
+ # Preset configurations
117
+ @classmethod
118
+ def ordinal_128m(cls): return cls(hidden_size=768, intermediate_size=2048, num_hidden_layers=12, num_attention_heads=12, num_key_value_heads=4, head_dim=64)
119
+ @classmethod
120
+ def ordinal_256m(cls): return cls(hidden_size=1024, intermediate_size=2816, num_hidden_layers=16, num_attention_heads=16, num_key_value_heads=4, head_dim=64)
121
+ @classmethod
122
+ def ordinal_512m(cls): return cls(hidden_size=1536, intermediate_size=4096, num_hidden_layers=20, num_attention_heads=16, num_key_value_heads=4, head_dim=96)
123
+ @classmethod
124
+ def ordinal_1b(cls): return cls(hidden_size=2048, intermediate_size=5504, num_hidden_layers=24, num_attention_heads=16, num_key_value_heads=4, head_dim=128)
125
+ @classmethod
126
+ def ordinal_2b(cls): return cls(hidden_size=2560, intermediate_size=6912, num_hidden_layers=28, num_attention_heads=20, num_key_value_heads=4, head_dim=128)
127
+ @classmethod
128
+ def ordinal_4b(cls): return cls(hidden_size=3072, intermediate_size=8192, num_hidden_layers=32, num_attention_heads=24, num_key_value_heads=4, head_dim=128)
129
+ @classmethod
130
+ def ordinal_5b(cls): return cls(hidden_size=3584, intermediate_size=9216, num_hidden_layers=36, num_attention_heads=28, num_key_value_heads=4, head_dim=128)
131
+ @classmethod
132
+ def ordinal_7b(cls): return cls(hidden_size=4096, intermediate_size=11008, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=8, head_dim=128)
133
+ @classmethod
134
+ def ordinal_13b(cls): return cls(hidden_size=5120, intermediate_size=13824, num_hidden_layers=40, num_attention_heads=40, num_key_value_heads=8, head_dim=128)
135
+ @classmethod
136
+ def ordinal_20b(cls): return cls(hidden_size=6144, intermediate_size=16384, num_hidden_layers=52, num_attention_heads=48, num_key_value_heads=8, head_dim=128)
137
+ @classmethod
138
+ def ordinal_33b(cls): return cls(hidden_size=6656, intermediate_size=17920, num_hidden_layers=64, num_attention_heads=56, num_key_value_heads=8, head_dim=128)
139
+ @classmethod
140
+ def ordinal_48b(cls): return cls(hidden_size=8192, intermediate_size=22016, num_hidden_layers=72, num_attention_heads=64, num_key_value_heads=8, head_dim=128)
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "do_sample": true,
7
+ "temperature": 0.7,
8
+ "top_p": 0.9,
9
+ "top_k": 40,
10
+ "max_new_tokens": 2048,
11
+ "repetition_penalty": 1.1,
12
+ "transformers_version": "4.45.0"
13
+ }
modeling_ordinal.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace-compatible modeling file for Ordinal LLM.
2
+
3
+ This file enables:
4
+ AutoModelForCausalLM.from_pretrained("KaztoRay/ordinal-5b", trust_remote_code=True)
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import json
11
+ from typing import Optional, Tuple
12
+ from dataclasses import dataclass
13
+
14
+
15
+ @dataclass
16
+ class OrdinalConfig:
17
+ """Configuration for Ordinal model (HuggingFace compatible)."""
18
+ model_type: str = "ordinal"
19
+ hidden_size: int = 3584
20
+ intermediate_size: int = 9216
21
+ num_hidden_layers: int = 36
22
+ num_attention_heads: int = 28
23
+ num_key_value_heads: int = 4
24
+ head_dim: int = 128
25
+ vocab_size: int = 50304
26
+ max_position_embeddings: int = 8192
27
+ rms_norm_eps: float = 1e-5
28
+ rope_theta: float = 500000.0
29
+ hidden_act: str = "silu"
30
+ tie_word_embeddings: bool = False
31
+ use_cache: bool = True
32
+ use_confidence_head: bool = True
33
+ confidence_threshold: float = 0.7
34
+ use_retrieval_attention: bool = True
35
+ retrieval_dim: int = 256
36
+ num_retrieval_heads: int = 4
37
+ use_fact_verification_layer: bool = True
38
+ verification_layers: list = None
39
+ use_source_embeddings: bool = True
40
+ num_source_types: int = 16
41
+ bos_token_id: int = 1
42
+ eos_token_id: int = 2
43
+ pad_token_id: int = 0
44
+ torch_dtype: str = "bfloat16"
45
+
46
+ def __post_init__(self):
47
+ if self.verification_layers is None:
48
+ n = self.num_hidden_layers
49
+ self.verification_layers = [n // 3, 2 * n // 3, n - 1]
50
+
51
+ @classmethod
52
+ def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
53
+ import os
54
+ config_path = os.path.join(pretrained_model_name_or_path, "config.json")
55
+ if os.path.exists(config_path):
56
+ with open(config_path) as f:
57
+ config_dict = json.load(f)
58
+ return cls(**{k: v for k, v in config_dict.items()
59
+ if k in cls.__dataclass_fields__})
60
+ return cls(**kwargs)
61
+
62
+
63
+ # Placeholder for actual model implementation (requires torch)
64
+ # The full implementation is in ordinal_llm/model/architecture/model.py
65
+ # This file provides the HuggingFace interface
66
+
67
+ try:
68
+ import torch
69
+ import torch.nn as nn
70
+ import torch.nn.functional as F
71
+ TORCH_AVAILABLE = True
72
+ except ImportError:
73
+ TORCH_AVAILABLE = False
74
+
75
+
76
+ if TORCH_AVAILABLE:
77
+ class OrdinalRMSNorm(nn.Module):
78
+ """Root Mean Square Layer Normalization."""
79
+ def __init__(self, hidden_size: int, eps: float = 1e-5):
80
+ super().__init__()
81
+ self.weight = nn.Parameter(torch.ones(hidden_size))
82
+ self.eps = eps
83
+
84
+ def forward(self, x):
85
+ variance = x.float().pow(2).mean(-1, keepdim=True)
86
+ x = x * torch.rsqrt(variance + self.eps)
87
+ return (self.weight * x).to(x.dtype)
88
+
89
+ class OrdinalRotaryEmbedding(nn.Module):
90
+ """Rotary Position Embedding (RoPE)."""
91
+ def __init__(self, dim: int, max_seq_len: int = 8192, theta: float = 500000.0):
92
+ super().__init__()
93
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
94
+ self.register_buffer("inv_freq", inv_freq)
95
+ t = torch.arange(max_seq_len).float()
96
+ freqs = torch.outer(t, inv_freq)
97
+ self.register_buffer("cos_cached", freqs.cos())
98
+ self.register_buffer("sin_cached", freqs.sin())
99
+
100
+ def forward(self, x, seq_len: int):
101
+ return self.cos_cached[:seq_len], self.sin_cached[:seq_len]
102
+
103
+ class OrdinalMLP(nn.Module):
104
+ """SwiGLU MLP."""
105
+ def __init__(self, config: OrdinalConfig):
106
+ super().__init__()
107
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
108
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
109
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
110
+
111
+ def forward(self, x):
112
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
113
+
114
+ class OrdinalAttention(nn.Module):
115
+ """Grouped Query Attention."""
116
+ def __init__(self, config: OrdinalConfig, layer_idx: int = 0):
117
+ super().__init__()
118
+ self.num_heads = config.num_attention_heads
119
+ self.num_kv_heads = config.num_key_value_heads
120
+ self.head_dim = config.head_dim
121
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
122
+
123
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
124
+ self.k_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
125
+ self.v_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
126
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
127
+ self.rotary = OrdinalRotaryEmbedding(self.head_dim, config.max_position_embeddings, config.rope_theta)
128
+
129
+ def forward(self, x, attention_mask=None, position_ids=None, past_key_value=None):
130
+ bsz, seq_len, _ = x.shape
131
+ q = self.q_proj(x).view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
132
+ k = self.k_proj(x).view(bsz, seq_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
133
+ v = self.v_proj(x).view(bsz, seq_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
134
+
135
+ # Apply RoPE
136
+ cos, sin = self.rotary(x, seq_len)
137
+ # Simplified RoPE application
138
+ q_embed = q * cos.unsqueeze(0).unsqueeze(0) + self._rotate_half(q) * sin.unsqueeze(0).unsqueeze(0)
139
+ k_embed = k * cos.unsqueeze(0).unsqueeze(0) + self._rotate_half(k) * sin.unsqueeze(0).unsqueeze(0)
140
+
141
+ # GQA: repeat KV heads
142
+ if self.num_kv_groups > 1:
143
+ k_embed = k_embed.repeat_interleave(self.num_kv_groups, dim=1)
144
+ v = v.repeat_interleave(self.num_kv_groups, dim=1)
145
+
146
+ # Attention
147
+ attn_weights = torch.matmul(q_embed, k_embed.transpose(-2, -1)) / math.sqrt(self.head_dim)
148
+ if attention_mask is not None:
149
+ attn_weights = attn_weights + attention_mask
150
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
151
+ attn_output = torch.matmul(attn_weights, v)
152
+
153
+ attn_output = attn_output.transpose(1, 2).reshape(bsz, seq_len, -1)
154
+ return self.o_proj(attn_output)
155
+
156
+ @staticmethod
157
+ def _rotate_half(x):
158
+ x1, x2 = x.chunk(2, dim=-1)
159
+ return torch.cat((-x2, x1), dim=-1)
160
+
161
+ class OrdinalDecoderLayer(nn.Module):
162
+ """Single transformer decoder layer."""
163
+ def __init__(self, config: OrdinalConfig, layer_idx: int = 0):
164
+ super().__init__()
165
+ self.self_attn = OrdinalAttention(config, layer_idx)
166
+ self.mlp = OrdinalMLP(config)
167
+ self.input_layernorm = OrdinalRMSNorm(config.hidden_size, config.rms_norm_eps)
168
+ self.post_attention_layernorm = OrdinalRMSNorm(config.hidden_size, config.rms_norm_eps)
169
+
170
+ def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None):
171
+ residual = hidden_states
172
+ hidden_states = self.input_layernorm(hidden_states)
173
+ hidden_states = self.self_attn(hidden_states, attention_mask, position_ids, past_key_value)
174
+ hidden_states = residual + hidden_states
175
+
176
+ residual = hidden_states
177
+ hidden_states = self.post_attention_layernorm(hidden_states)
178
+ hidden_states = self.mlp(hidden_states)
179
+ hidden_states = residual + hidden_states
180
+ return hidden_states
181
+
182
+ class OrdinalConfidenceHead(nn.Module):
183
+ """Per-token confidence scoring (anti-hallucination)."""
184
+ def __init__(self, hidden_size: int):
185
+ super().__init__()
186
+ self.linear1 = nn.Linear(hidden_size, hidden_size // 4)
187
+ self.linear2 = nn.Linear(hidden_size // 4, 1)
188
+
189
+ def forward(self, hidden_states):
190
+ x = F.gelu(self.linear1(hidden_states))
191
+ return torch.sigmoid(self.linear2(x))
192
+
193
+ class OrdinalModel(nn.Module):
194
+ """Ordinal base model (transformer decoder)."""
195
+ def __init__(self, config: OrdinalConfig):
196
+ super().__init__()
197
+ self.config = config
198
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
199
+ self.layers = nn.ModuleList([
200
+ OrdinalDecoderLayer(config, i) for i in range(config.num_hidden_layers)
201
+ ])
202
+ self.norm = OrdinalRMSNorm(config.hidden_size, config.rms_norm_eps)
203
+
204
+ def forward(self, input_ids, attention_mask=None, position_ids=None):
205
+ hidden_states = self.embed_tokens(input_ids)
206
+ for layer in self.layers:
207
+ hidden_states = layer(hidden_states, attention_mask, position_ids)
208
+ return self.norm(hidden_states)
209
+
210
+ class OrdinalForCausalLM(nn.Module):
211
+ """Ordinal model for causal language modeling (HF compatible)."""
212
+ def __init__(self, config: OrdinalConfig):
213
+ super().__init__()
214
+ self.config = config
215
+ self.model = OrdinalModel(config)
216
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
217
+ if config.use_confidence_head:
218
+ self.confidence_head = OrdinalConfidenceHead(config.hidden_size)
219
+ if config.tie_word_embeddings:
220
+ self.lm_head.weight = self.model.embed_tokens.weight
221
+
222
+ def forward(self, input_ids, attention_mask=None, labels=None, **kwargs):
223
+ hidden_states = self.model(input_ids, attention_mask)
224
+ logits = self.lm_head(hidden_states)
225
+
226
+ loss = None
227
+ if labels is not None:
228
+ shift_logits = logits[..., :-1, :].contiguous()
229
+ shift_labels = labels[..., 1:].contiguous()
230
+ loss = F.cross_entropy(
231
+ shift_logits.view(-1, self.config.vocab_size),
232
+ shift_labels.view(-1),
233
+ ignore_index=-100,
234
+ )
235
+
236
+ confidence = None
237
+ if hasattr(self, 'confidence_head'):
238
+ confidence = self.confidence_head(hidden_states)
239
+
240
+ return {"loss": loss, "logits": logits, "confidence": confidence}
241
+
242
+ def generate(self, input_ids, max_new_tokens=512, temperature=0.7, top_p=0.9, **kwargs):
243
+ """Simple autoregressive generation."""
244
+ for _ in range(max_new_tokens):
245
+ outputs = self.forward(input_ids)
246
+ logits = outputs["logits"][:, -1, :] / temperature
247
+
248
+ # Top-p sampling
249
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
250
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
251
+ sorted_indices_to_remove = cumulative_probs > top_p
252
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
253
+ sorted_indices_to_remove[..., 0] = 0
254
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
255
+ logits[indices_to_remove] = float('-inf')
256
+
257
+ probs = F.softmax(logits, dim=-1)
258
+ next_token = torch.multinomial(probs, num_samples=1)
259
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
260
+
261
+ if next_token.item() == self.config.eos_token_id:
262
+ break
263
+
264
+ # Confidence-aware: reduce temperature if uncertain
265
+ if hasattr(self, 'confidence_head'):
266
+ conf = outputs["confidence"][:, -1, 0]
267
+ if conf.item() < self.config.confidence_threshold:
268
+ temperature = max(0.3, temperature * 0.9)
269
+
270
+ return input_ids
271
+
272
+ @classmethod
273
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
274
+ config = OrdinalConfig.from_pretrained(pretrained_model_name_or_path)
275
+ model = cls(config)
276
+ # Load weights if available
277
+ import os
278
+ for weight_file in ["model.safetensors", "pytorch_model.bin"]:
279
+ path = os.path.join(pretrained_model_name_or_path, weight_file)
280
+ if os.path.exists(path):
281
+ if weight_file.endswith(".safetensors"):
282
+ from safetensors.torch import load_file
283
+ state_dict = load_file(path)
284
+ else:
285
+ state_dict = torch.load(path, map_location="cpu")
286
+ model.load_state_dict(state_dict, strict=False)
287
+ break
288
+ return model
289
+
290
+ def num_parameters(self, only_trainable: bool = False):
291
+ return sum(p.numel() for p in self.parameters() if p.requires_grad or not only_trainable)
special_tokens_map.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin|>",
4
+ "lstrip": false,
5
+ "rstrip": false,
6
+ "single_word": false,
7
+ "normalized": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|end|>",
11
+ "lstrip": false,
12
+ "rstrip": false,
13
+ "single_word": false,
14
+ "normalized": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|pad|>",
18
+ "lstrip": false,
19
+ "rstrip": false,
20
+ "single_word": false,
21
+ "normalized": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<|unk|>",
25
+ "lstrip": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "normalized": false
29
+ },
30
+ "additional_special_tokens": [
31
+ "<|system|>",
32
+ "<|user|>",
33
+ "<|assistant|>",
34
+ "<|end_turn|>",
35
+ "<|cve|>",
36
+ "<|mitre|>",
37
+ "<|cwe|>",
38
+ "<|capec|>",
39
+ "<|ioc|>",
40
+ "<|ip|>",
41
+ "<|hash|>",
42
+ "<|domain|>",
43
+ "<|confidence_high|>",
44
+ "<|confidence_medium|>",
45
+ "<|confidence_low|>",
46
+ "<|source_verified|>",
47
+ "<|source_unverified|>",
48
+ "<|code_start|>",
49
+ "<|code_end|>",
50
+ "<|thinking|>",
51
+ "<|end_thinking|>"
52
+ ]
53
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "ordinal",
3
+ "bos_token": "<|begin|>",
4
+ "eos_token": "<|end|>",
5
+ "pad_token": "<|pad|>",
6
+ "unk_token": "<|unk|>",
7
+ "chat_template": "{% for message in messages %}<|{{ message.role }}|>\n{{ message.content }}<|end_turn|>\n{% endfor %}{% if add_generation_prompt %}<|assistant|>\n{% endif %}",
8
+ "model_max_length": 8192,
9
+ "padding_side": "left",
10
+ "truncation_side": "left"
11
+ }