Text Generation
Transformers
Safetensors
PyTorch
ONNX
English
qtensorformer
q-tensorformer
high-throughput-inference
tensor-train
tensor-networks
tensorrt-llm
vllm
continuous-batching
paged-attention
speculative-decoding
zero-svd
adaptive-computation
dynamic-neural-networks
kv-cache
kv-cache-quantization
attention-sinks
lyapunov-stability
control-theory
contextual-bandits
edge-ai
edge-inference
on-device-ai
model-compression
hopper-h100
blackwell-b200
jetson-orin
jetson-thor
grouped-query-attention
rotary-position-embeddings
custom_code
academic-paper
ieee
neurips
vit-ap-university
deepseek
deepseek-r1
reasoning
chain-of-thought
gsm8k
openai-compatible
fastapi
rest-api
sse-streaming
onnx-runtime
embedded-ai
hardware-telemetry
power-efficiency
green-ai
raspberry-pi
smollm2
qwen2.5
llama-3.2
apple-silicon
Instructions to use Premchan369/Q-TensorFormer with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Premchan369/Q-TensorFormer with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Premchan369/Q-TensorFormer", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Premchan369/Q-TensorFormer", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Premchan369/Q-TensorFormer with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Premchan369/Q-TensorFormer" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Premchan369/Q-TensorFormer", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Premchan369/Q-TensorFormer
- SGLang
How to use Premchan369/Q-TensorFormer 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 "Premchan369/Q-TensorFormer" \ --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": "Premchan369/Q-TensorFormer", "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 "Premchan369/Q-TensorFormer" \ --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": "Premchan369/Q-TensorFormer", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Premchan369/Q-TensorFormer with Docker Model Runner:
docker model run hf.co/Premchan369/Q-TensorFormer
File size: 5,946 Bytes
b5cb5a0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | """
src/semantic_kv_cache.py
Entropy-Gated Semantic Anchor KV-Cache for Q-TensorFormer.
Protects initial attention sinks AND high-entropy / high-surprise tokens (semantic anchors)
from cache eviction, while aggressively quantizing or evicting low-information filler tokens.
Prevents long-context reasoning collapse while slashing DRAM footprint by up to 90%+.
"""
from typing import Dict, Any, List, Set, Optional, Tuple
import math
import torch
import torch.nn as nn
from src.kv_cache import AdaptiveKVCache, KVPrecision, QuantizedKVTensor
class SemanticAnchorKVCache:
"""
Entropy & Surprise Gated KV Cache with Semantic Anchor Protection.
Protects:
1. Attention Sinks (positions 0 .. sink_size - 1)
2. Semantic Anchors (positions with entropy >= entropy_threshold or surprise >= surprise_threshold)
Evicts:
3. Uninformative filler tokens when capacity reaches max_capacity.
"""
def __init__(
self,
max_capacity: int = 128,
sink_size: int = 4,
entropy_threshold: float = 2.5,
surprise_threshold: float = 3.0,
default_precision: KVPrecision = KVPrecision.INT8,
):
self.max_capacity = max_capacity
self.sink_size = sink_size
self.entropy_threshold = entropy_threshold
self.surprise_threshold = surprise_threshold
self.default_precision = default_precision
# Storage
self.keys: List[torch.Tensor] = []
self.values: List[torch.Tensor] = []
self.anchor_indices: Set[int] = set()
self.token_positions: List[int] = []
self.token_entropies: List[float] = []
def append(
self,
key: torch.Tensor,
value: torch.Tensor,
entropy: float = 0.0,
surprise: float = 0.0,
attention_score: float = 1.0,
) -> Dict[str, Any]:
"""
Appends key/value tensors for a new token, evaluating whether to declare it a semantic anchor.
Args:
key: Tensor of shape (B, H, 1, D)
value: Tensor of shape (B, H, 1, D)
entropy: Predictive entropy of token distribution
surprise: Negative log-likelihood of selected token
attention_score: Cumulative attention received by this token
"""
current_seq_pos = len(self.token_positions)
is_sink = current_seq_pos < self.sink_size
is_anchor = (entropy >= self.entropy_threshold) or (surprise >= self.surprise_threshold)
if is_sink or is_anchor:
self.anchor_indices.add(current_seq_pos)
self.keys.append(key)
self.values.append(value)
self.token_positions.append(current_seq_pos)
self.token_entropies.append(entropy)
# Evict if exceeding max_capacity
evicted_pos = None
if len(self.keys) > self.max_capacity:
# Find earliest non-anchor, non-sink token to evict
evict_idx = -1
for idx, pos in enumerate(self.token_positions):
if pos not in self.anchor_indices:
evict_idx = idx
break
if evict_idx != -1:
evicted_pos = self.token_positions.pop(evict_idx)
self.keys.pop(evict_idx)
self.values.pop(evict_idx)
self.token_entropies.pop(evict_idx)
else:
# If all tokens are anchors, evict the lowest entropy anchor beyond sinks
best_candidate = -1
lowest_entropy = float("inf")
for idx, pos in enumerate(self.token_positions):
if pos >= self.sink_size and self.token_entropies[idx] < lowest_entropy:
lowest_entropy = self.token_entropies[idx]
best_candidate = idx
if best_candidate != -1:
evicted_pos = self.token_positions.pop(best_candidate)
self.keys.pop(best_candidate)
self.values.pop(best_candidate)
self.token_entropies.pop(best_candidate)
self.anchor_indices.discard(evicted_pos)
return {
"position": current_seq_pos,
"is_sink": is_sink,
"is_anchor": is_anchor,
"evicted_position": evicted_pos,
"cached_tokens": len(self.keys),
"protected_anchors": len([p for p in self.token_positions if p in self.anchor_indices]),
}
def get_kv(self) -> Tuple[torch.Tensor, torch.Tensor]:
"""Concatenates all active keys and values along sequence dimension (dim=2)."""
if not self.keys:
raise ValueError("KV cache is empty.")
k = torch.cat(self.keys, dim=2)
v = torch.cat(self.values, dim=2)
return k, v
def memory_footprint_bytes(self) -> int:
"""Calculates total physical bytes used by active keys and values."""
if not self.keys:
return 0
element_size = 2 if self.default_precision == KVPrecision.FP16 else 1
num_elements = sum(k.numel() + v.numel() for k, v in zip(self.keys, self.values))
return num_elements * element_size
def evaluate_retrieval_retention(
self,
needle_positions: List[int],
) -> Dict[str, Any]:
"""
Evaluates whether needle token positions were successfully retained in cache.
"""
cached_set = set(self.token_positions)
retained = [pos for pos in needle_positions if pos in cached_set]
retention_rate = len(retained) / max(1, len(needle_positions))
return {
"total_needles": len(needle_positions),
"retained_needles": len(retained),
"retention_rate": retention_rate,
"cached_token_count": len(self.token_positions),
"max_capacity": self.max_capacity,
"scientific_classification": "MEASURED",
}
|