Text Generation
Transformers
Safetensors
PyTorch
English
hfp
causal-lm
linear-attention
long-context
recurrent-memory
o1-memory
custom_code
Instructions to use kayrahan35/HFP-O1-Memory-Model with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use kayrahan35/HFP-O1-Memory-Model with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="kayrahan35/HFP-O1-Memory-Model", trust_remote_code=True)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("kayrahan35/HFP-O1-Memory-Model", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use kayrahan35/HFP-O1-Memory-Model with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "kayrahan35/HFP-O1-Memory-Model" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "kayrahan35/HFP-O1-Memory-Model", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/kayrahan35/HFP-O1-Memory-Model
- SGLang
How to use kayrahan35/HFP-O1-Memory-Model with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "kayrahan35/HFP-O1-Memory-Model" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "kayrahan35/HFP-O1-Memory-Model", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "kayrahan35/HFP-O1-Memory-Model" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "kayrahan35/HFP-O1-Memory-Model", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use kayrahan35/HFP-O1-Memory-Model with Docker Model Runner:
docker model run hf.co/kayrahan35/HFP-O1-Memory-Model
Delete modeling_hfp.py
Browse files- modeling_hfp.py +0 -232
modeling_hfp.py
DELETED
|
@@ -1,232 +0,0 @@
|
|
| 1 |
-
# Hyper Flux Projection (HFP) — O(1)-memory causal language model
|
| 2 |
-
# Copyright (C) 2026 Kayrahan Yılmaz
|
| 3 |
-
#
|
| 4 |
-
# This program is free software: you can redistribute it and/or modify
|
| 5 |
-
# it under the terms of the GNU Affero General Public License as published
|
| 6 |
-
# by the Free Software Foundation, either version 3 of the License, or
|
| 7 |
-
# (at your option) any later version.
|
| 8 |
-
#
|
| 9 |
-
# This program is distributed in the hope that it will be useful,
|
| 10 |
-
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 11 |
-
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 12 |
-
# GNU Affero General Public License for more details.
|
| 13 |
-
#
|
| 14 |
-
# You should have received a copy of the GNU Affero General Public License
|
| 15 |
-
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 16 |
-
|
| 17 |
-
import torch
|
| 18 |
-
import torch.nn as nn
|
| 19 |
-
import math
|
| 20 |
-
from transformers import PreTrainedModel
|
| 21 |
-
from transformers.modeling_outputs import CausalLMOutputWithPast, BaseModelOutputWithPast
|
| 22 |
-
from .configuration_hfp import HFPConfig
|
| 23 |
-
|
| 24 |
-
from .hfp_bulk_state import HFPBulkState
|
| 25 |
-
from .bulk_trigger_decoder import BulkTriggerDecoderLayer
|
| 26 |
-
|
| 27 |
-
class SinusoidalPositionalEncoding(nn.Module):
|
| 28 |
-
def __init__(self, hidden_size, max_len=5000, pe_scale=0.3):
|
| 29 |
-
super().__init__()
|
| 30 |
-
self.max_len = max_len
|
| 31 |
-
# [FIX K7] PE olcegi. Onceden ham (norm=sqrt(d/2)=8) eklenirken embedding
|
| 32 |
-
# normu 0.02*sqrt(d)=0.23 idi -> PE, token icerigini ~35x BOGUYORDU;
|
| 33 |
-
# anahtar/deger'ler ~%97 pozisyon oluyor, icerik-tabanli recall imkansiz
|
| 34 |
-
# (MQAR loss ln(val_space)'te sabitlenip binding hic ogrenilmiyordu).
|
| 35 |
-
# embed *sqrt(d) (bkz. HFPModel) + PE *0.3 ile normlar dengelenir.
|
| 36 |
-
self.pe_scale = pe_scale
|
| 37 |
-
pe = torch.zeros(max_len, hidden_size)
|
| 38 |
-
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
|
| 39 |
-
div_term = torch.exp(torch.arange(0, hidden_size, 2).float() * (-math.log(10000.0) / hidden_size))
|
| 40 |
-
pe[:, 0::2] = torch.sin(position * div_term)
|
| 41 |
-
pe[:, 1::2] = torch.cos(position * div_term)
|
| 42 |
-
self.register_buffer('pe', pe.unsqueeze(0))
|
| 43 |
-
|
| 44 |
-
def forward(self, x, offset: int = 0):
|
| 45 |
-
# [FIX A2] Streaming/chunked prefill'de her chunk'a 0..L degil, GLOBAL pozisyon eklenir.
|
| 46 |
-
seq_len = x.size(1)
|
| 47 |
-
if offset + seq_len > self.max_len:
|
| 48 |
-
offset = max(0, self.max_len - seq_len)
|
| 49 |
-
return x + self.pe_scale * self.pe[:, offset:offset + seq_len, :].to(x.device)
|
| 50 |
-
|
| 51 |
-
class HFPPreTrainedModel(PreTrainedModel):
|
| 52 |
-
config_class = HFPConfig
|
| 53 |
-
base_model_prefix = "hfp"
|
| 54 |
-
_supports_cache_class = False
|
| 55 |
-
|
| 56 |
-
def _init_weights(self, module):
|
| 57 |
-
if isinstance(module, nn.Linear):
|
| 58 |
-
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 59 |
-
if module.bias is not None:
|
| 60 |
-
# importance_gate bias'i bilerek -2.0 (gate-collapse onlemi); ezme.
|
| 61 |
-
if torch.all(module.bias.data == -2.0):
|
| 62 |
-
pass
|
| 63 |
-
else:
|
| 64 |
-
module.bias.data.zero_()
|
| 65 |
-
elif isinstance(module, nn.Embedding):
|
| 66 |
-
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 67 |
-
if module.padding_idx is not None:
|
| 68 |
-
module.weight.data[module.padding_idx].zero_()
|
| 69 |
-
elif isinstance(module, nn.LayerNorm):
|
| 70 |
-
module.bias.data.zero_()
|
| 71 |
-
module.weight.data.fill_(1.0)
|
| 72 |
-
|
| 73 |
-
class HFPModel(HFPPreTrainedModel):
|
| 74 |
-
def __init__(self, config):
|
| 75 |
-
super().__init__(config)
|
| 76 |
-
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 77 |
-
# [FIX K7] Vaswani sqrt(d) olcegi: emb (init std 0.02) tek basina norm~0.23;
|
| 78 |
-
# sqrt(d) ile ~2.56'ya cikar ve sonuchennmus PE (*0.3, norm~2.4) ile dengelenir.
|
| 79 |
-
self.embed_scale = math.sqrt(config.hidden_size)
|
| 80 |
-
self.pos_encoder = SinusoidalPositionalEncoding(
|
| 81 |
-
config.hidden_size, max_len=config.max_position_embeddings,
|
| 82 |
-
pe_scale=getattr(config, "pe_scale", 0.3))
|
| 83 |
-
|
| 84 |
-
self.layers = nn.ModuleList([
|
| 85 |
-
BulkTriggerDecoderLayer(
|
| 86 |
-
hidden_size=config.hidden_size,
|
| 87 |
-
num_heads=config.num_attention_heads,
|
| 88 |
-
feedforward_dim=config.intermediate_size,
|
| 89 |
-
bulk_dim=config.bulk_dim,
|
| 90 |
-
vocab_size=None,
|
| 91 |
-
local_window=getattr(config, "local_window", None), # [FIX K5]
|
| 92 |
-
dropout_p=getattr(config, "dropout_p", 0.1), # [FIX K3]
|
| 93 |
-
ffn_type=getattr(config, "ffn_type", "entangled") # [HFP-SCALE]
|
| 94 |
-
)
|
| 95 |
-
for _ in range(config.num_hidden_layers)
|
| 96 |
-
])
|
| 97 |
-
|
| 98 |
-
# Katman-basi recurrent bellek (physics-inspired 'Bulk' analojisi;
|
| 99 |
-
# teknik olarak: decay'li lineer-attention state'i M, z)
|
| 100 |
-
# [TEMIZLIK B1] medium_freq/long_freq/medium_momentum kaldirildi.
|
| 101 |
-
self.bulk_states = nn.ModuleList([
|
| 102 |
-
HFPBulkState(
|
| 103 |
-
hidden_size=config.hidden_size,
|
| 104 |
-
short_len=config.short_len,
|
| 105 |
-
max_short_len=getattr(config, "max_short_len", None), # [FIX K4]
|
| 106 |
-
rec_block=getattr(config, "rec_block", 64), # [K2]
|
| 107 |
-
decay_mode=getattr(config, "decay_mode", "exp"), # [HFP-CORE]
|
| 108 |
-
conv_kernel=getattr(config, "conv_kernel", 3), # [FIX K8] binding
|
| 109 |
-
key_feature_map=getattr(config, "key_feature_map", "elu"), # [HFP-CAP]
|
| 110 |
-
dpfp_nu=getattr(config, "dpfp_nu", 2), # [HFP-CAP]
|
| 111 |
-
write_rule=getattr(config, "write_rule", "additive") # [HFP-DELTA]
|
| 112 |
-
)
|
| 113 |
-
for _ in range(config.num_hidden_layers)
|
| 114 |
-
])
|
| 115 |
-
# [K2] TBPTT: True ise chunk'lar arasi state detach edilmez
|
| 116 |
-
self._detach_state = not getattr(config, "bptt_across_chunks", False)
|
| 117 |
-
|
| 118 |
-
self.norm = nn.LayerNorm(config.hidden_size)
|
| 119 |
-
self.post_init()
|
| 120 |
-
|
| 121 |
-
@staticmethod
|
| 122 |
-
def _offset_from_state(past_key_values_list):
|
| 123 |
-
# state tuple: (short_memory, M, z, token_count, short_len_dynamic, write_idx, conv_state)
|
| 124 |
-
first = past_key_values_list[0]
|
| 125 |
-
if first is not None and len(first) >= 4 and isinstance(first[3], int):
|
| 126 |
-
return int(first[3])
|
| 127 |
-
return 0
|
| 128 |
-
|
| 129 |
-
def forward(self, input_ids, attention_mask=None, past_key_values=None, use_cache=False, **kwargs):
|
| 130 |
-
x = self.embed_tokens(input_ids) * self.embed_scale # [FIX K7]
|
| 131 |
-
|
| 132 |
-
if past_key_values is None or not isinstance(past_key_values, (tuple, list)):
|
| 133 |
-
past_key_values_list = [None] * len(self.layers)
|
| 134 |
-
else:
|
| 135 |
-
past_key_values_list = past_key_values
|
| 136 |
-
|
| 137 |
-
# [FIX A2] Global pozisyon offseti (chunked prefill icin)
|
| 138 |
-
offset = self._offset_from_state(past_key_values_list)
|
| 139 |
-
x = self.pos_encoder(x, offset=offset)
|
| 140 |
-
|
| 141 |
-
new_past_key_values = []
|
| 142 |
-
gate_entropies = []
|
| 143 |
-
for i, (layer, bulk_state) in enumerate(zip(self.layers, self.bulk_states)):
|
| 144 |
-
x, _, new_past_state = layer(x, bulk_state, past_state=past_key_values_list[i],
|
| 145 |
-
return_past_state=True, detach_state=self._detach_state)
|
| 146 |
-
|
| 147 |
-
# [C1] Gradyanli gate-entropy topla (yalnizca agirlik > 0 iken loss'a katilir)
|
| 148 |
-
if self.training and getattr(bulk_state, "_gate_entropy_live", None) is not None:
|
| 149 |
-
gate_entropies.append(bulk_state._gate_entropy_live)
|
| 150 |
-
|
| 151 |
-
if use_cache:
|
| 152 |
-
new_past_key_values.append(new_past_state)
|
| 153 |
-
|
| 154 |
-
x = self.norm(x)
|
| 155 |
-
|
| 156 |
-
out = BaseModelOutputWithPast(
|
| 157 |
-
last_hidden_state=x,
|
| 158 |
-
past_key_values=new_past_key_values if use_cache else None
|
| 159 |
-
)
|
| 160 |
-
out.gate_entropy = (torch.stack(gate_entropies).mean() if gate_entropies else None)
|
| 161 |
-
return out
|
| 162 |
-
|
| 163 |
-
from transformers.generation import GenerationMixin
|
| 164 |
-
|
| 165 |
-
class HFPForCausalLM(HFPPreTrainedModel, GenerationMixin):
|
| 166 |
-
# [D1] lm_head, embed_tokens'a bagli (weight tying) — safetensors kaydinin
|
| 167 |
-
# paylasilan tensoru dogru ele almasi icin bildirilmeli.
|
| 168 |
-
# transformers v5: dict (hedef -> kaynak); v4'te de sorunsuz calisir.
|
| 169 |
-
_tied_weights_keys = {"lm_head.weight": "hfp.embed_tokens.weight"}
|
| 170 |
-
|
| 171 |
-
def __init__(self, config):
|
| 172 |
-
super().__init__(config)
|
| 173 |
-
self.hfp = HFPModel(config)
|
| 174 |
-
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 175 |
-
# [D1] Weight tying (GPT standardi): embedding ve lm_head paylasimi
|
| 176 |
-
self.lm_head.weight = self.hfp.embed_tokens.weight
|
| 177 |
-
self.post_init()
|
| 178 |
-
|
| 179 |
-
# [D1] tie_weights()'in from_pretrained SONRASI baglantiyi yeniden kurabilmesi
|
| 180 |
-
# icin standart erisimciler (bunlarsiz yukleme tying'i sessizce koparir).
|
| 181 |
-
def get_input_embeddings(self):
|
| 182 |
-
return self.hfp.embed_tokens
|
| 183 |
-
|
| 184 |
-
def set_input_embeddings(self, value):
|
| 185 |
-
self.hfp.embed_tokens = value
|
| 186 |
-
|
| 187 |
-
def get_output_embeddings(self):
|
| 188 |
-
return self.lm_head
|
| 189 |
-
|
| 190 |
-
def set_output_embeddings(self, value):
|
| 191 |
-
self.lm_head = value
|
| 192 |
-
|
| 193 |
-
def forward(self, input_ids, attention_mask=None, labels=None, past_key_values=None, use_cache=False, **kwargs):
|
| 194 |
-
outputs = self.hfp(input_ids, attention_mask=attention_mask, past_key_values=past_key_values, use_cache=use_cache, **kwargs)
|
| 195 |
-
hidden_states = outputs.last_hidden_state
|
| 196 |
-
logits = self.lm_head(hidden_states)
|
| 197 |
-
|
| 198 |
-
loss = None
|
| 199 |
-
if labels is not None:
|
| 200 |
-
shift_logits = logits[..., :-1, :].contiguous()
|
| 201 |
-
shift_labels = labels[..., 1:].contiguous()
|
| 202 |
-
loss_fct = nn.CrossEntropyLoss()
|
| 203 |
-
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
|
| 204 |
-
|
| 205 |
-
# [C1] Opsiyonel gate-entropy duzenleyici - default kapali (weight=0.0).
|
| 206 |
-
w = float(getattr(self.config, "aux_gate_entropy_weight", 0.0))
|
| 207 |
-
if w > 0.0 and getattr(outputs, "gate_entropy", None) is not None:
|
| 208 |
-
loss = loss + w * outputs.gate_entropy
|
| 209 |
-
|
| 210 |
-
# [ORTHO] EntangledFFN ortogonallik duzenleyicisi. Paylasilan W_bulk'tan
|
| 211 |
-
# turetilen P_A/P_B'nin farkli ("tek bulk'in iki ayri golgesi") kalmasi
|
| 212 |
-
# icin baski. Onceden implement edilmis ama loss'a HIC bagli degildi
|
| 213 |
-
# (olu kod); artik opsiyonel + default kapali (weight=0.0 => baseline degismez).
|
| 214 |
-
w_o = float(getattr(self.config, "aux_ortho_weight", 0.0))
|
| 215 |
-
if w_o > 0.0:
|
| 216 |
-
ortho = sum(layer.ffn.get_orthogonality_loss() for layer in self.hfp.layers)
|
| 217 |
-
loss = loss + w_o * ortho
|
| 218 |
-
|
| 219 |
-
return CausalLMOutputWithPast(
|
| 220 |
-
loss=loss,
|
| 221 |
-
logits=logits,
|
| 222 |
-
past_key_values=outputs.past_key_values
|
| 223 |
-
)
|
| 224 |
-
|
| 225 |
-
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
|
| 226 |
-
if past_key_values:
|
| 227 |
-
input_ids = input_ids[:, -1:]
|
| 228 |
-
return {
|
| 229 |
-
"input_ids": input_ids,
|
| 230 |
-
"past_key_values": past_key_values,
|
| 231 |
-
"use_cache": kwargs.get("use_cache", True)
|
| 232 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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