Text Generation
Transformers
Safetensors
PyTorch
ONNX
English
qtensorformer
qtf
q-tensorformer
qtensor
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
Premchandyadav369 commited on
Commit ·
c5356b0
1
Parent(s): eaeea8f
Enhance README.md with comprehensive LaTeX equations and theoretical CMDP formulation
Browse files32 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969710 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491507 unmodified lines15815916016116216316432 unmodified lines---## 🏆 Research Contribution & ThesisExisting efficient Transformer methods treat model compression, adaptive depth, and KV-cache optimization as isolated, uncoordinated heuristics:* **Tensor-Train (TT)** compresses weight matrices statically, ignoring token-specific representation needs.* **Dynamic computation** (early exit, token dropping) often introduces top-$k$ routing overhead, dynamic tensor shape churn, and tail latency inflation without reducing actual DRAM memory traffic.* **KV-cache compression** (quantization, eviction) operates at runtime without coordination with weight capacity.**Q-TensorFormer** unifies these components into a single **closed-loop economic optimization framework**:$$\text{Value}(a \mid z_t) = \frac{\widehat{\Delta Q}(a \mid z_t)}{\Delta C_{\text{latency}}(a) + \lambda_m \Delta C_{\text{memory}}(a) + \lambda_e \Delta C_{\text{energy}}(a) + \lambda_b \Delta C_{\text{bandwidth}}(a) + \epsilon}$$The model does not merely ask *"How complex is this token?"* It asks:> **"Given what is known about this token ($z_t$), the current model state, the remaining KV capacity, and the measured hardware profile, what is the cheapest additional computation that yields the greatest expected marginal improvement?"**---## 📐 Architecture Overview```textINPUT TOKENS│▼┌─────────────────────────────────────────────────────────────┐│ 1. TOKEN INFORMATION STATE (z_t) ││ - Predictive logit entropy H_t (model confidence) ││ - Entanglement / attention dispersion S_t (spread) ││ - Epistemic uncertainty U_t (representation variance) ││ - Attention importance A_t (incoming query mass) ││ - Tensor-Train reconstruction residual R_t ││ - Measured hardware pressures [L_t, M_t, B_t] │└──────────────────────────────┬──────────────────────────────┘│▼┌───────────────────────────────────────────────────────────��─┐│ 2. INFORMATION-VALUE RESOURCE ALLOCATOR ││ - Predicts marginal utility Value(a | z_t) ││ - Action a = (TT Rank, Attn Pathway, Depth, KV Policy) ││ - Hysteresis Anti-Chattering: a_t = a_{t-1} if |Δu| < τ │└──────────────────────────────┬──────────────────────────────┘│▼┌─────────────────────────────────────────────────────────────┐│ 3. EMPIRICAL HARDWARE COST MODEL ││ - Calibrated wall-clock latency predictor L_hat ││ - DRAM memory traffic profiler (bytes read / written) ││ - Multi-level energy profiler (Levels 1 to 4) │└──────────────────────────────┬──────────────────────────────┘│▼┌─────────────────────────────────────────────────────────────┐│ 4. JOINT EXECUTION ENGINE ││ ├── Weight Path: Nested TT Cores (Ranks 1, 2, 4, 8) ││ ├── Attention Path: Classical Fast-SDPA vs QKSAM VQC ││ ├── Memory Path: Dynamic KV Cache (FP16/INT8/INT4/Evict) ││ └── Quantum Backend: Simulator / Classical Surrogate │└─────────────────────────────────────────────────────────────┘```---## 📊 Standardized Comparative Benchmark*All metrics rigorously classified as **MEASURED** (empirical hardware profiling), **ESTIMATED** (calibrated model), or **PROJECTED** (analytical scaling).*10 unmodified lines---## 🔑 Key Innovations & Empirical Findings### 1. Nested-Core Dynamic Rank Execution (Zero-SVD Overhead)Earlier iterations relied on runtime Singular Value Decomposition (`torch.linalg.svd`) to alter tensor rank, causing massive runtime stalls. Q-TensorFormer implements **Nested-Core Slicing**:* Cores are allocated at bond dimension $r_{\max}=8$: $G^{(k)} \in \mathbb{R}^{r_{\max} \times d_o \times d_i \times r_{\max}}$.* At runtime, active rank $r \in \{1, 2, 4, 8\}$ is executed instantaneously via tensor view slicing: $G^{(k)}[:r_l, :, :, :r_r]$.* **Overhead: 0.00 ms** (instantaneous stride slicing).### 2. Adaptive KV Cache & Memory Traffic Optimization* KV memory is reduced by **3.2× to 4.0×** via asymmetric INT4 and INT8 quantization without perplexity degradation.* Dynamic attention-utility eviction automatically retains prompt sink tokens and high-importance tokens while pruning redundant history.### 3. Conditional Quantum Acceleration (QKSAM)* The Quantum Kernel Self-Attention (QKSAM) kernel $K(q, k) = |\langle \phi(q)|\phi(k)\rangle|^2$ provides higher representation fidelity for ambiguous tokens.* **Empirical Reality**: Classical simulation of quantum circuits on CPUs incurs substantial execution overhead. Rather than hiding this, Q-TensorFormer's allocator learns that quantum computation has negative marginal utility for simple tokens, activating it only for tokens with uncertainty $> 0.75$.* Comes with a high-performance **Classical Surrogate Backend** that emulates unitary group rotations at native CPU speeds.### 4. Routing Hysteresis & Stability* Dynamic token-routing often causes destructive "route chattering" (alternating between ranks each token).* By enforcing hysteresis ($a_t = a_{t-1}$ if $|\Delta \text{Value}| < \tau$), **routing churn is reduced by 81%**, eliminating tail latency spikes.---## 🚀 Quick Start: Hugging Face IntegrationQ-TensorFormer is fully integrated into the Hugging Face `transformers` ecosystem:```pythonfrom transformers import AutoConfig, AutoModelForCausalLMimport src # Registers 'qtensorformer'# 1. Load configuration and model directlyconfig = AutoConfig.from_pretrained("Premchan369/Q-TensorFormer")model = AutoModelForCausalLM.from_pretrained("Premchan369/Q-TensorFormer")# 2. Select a deployment preset# Options: 'full', 'balanced', 'latency', 'memory', 'energy', 'edge', 'classical_only'model.set_preset("balanced")# 3. Autoregressive Generation with Adaptive KV Cache7 unmodified lines## 🧪 Reproducible Research ExperimentsAll experimental claims are verifiable via standalone one-command runners:```bash# 1. Standardized Baselines Comparison (Table 1)32 unmodified lines3334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919010 unmodified lines2012022032042052062072082092102112122132142152162172182192207 unmodified lines22822923023123223323432 unmodified lines---## 🏆 Theoretical Foundation & Research ThesisConventional efficient Transformer methodologies treat model compression, adaptive depth, and KV-cache optimization as isolated, uncoordinated heuristics:* **Tensor-Train (TT)** compresses weight matrices statically, ignoring token-specific representation needs.* **Dynamic computation** (early exit, token dropping) often introduces top-$k$ routing overhead, dynamic tensor shape churn, and tail latency inflation without reducing DRAM memory traffic.* **KV-cache compression** (quantization, eviction) operates at runtime without coordination with weight capacity.### 1. The Constrained Information-Resource Optimization ProblemWe formalize inference resource allocation as a **Constrained Markov Decision Process (CMDP)** over token sequence $x_{1:T}$. For a model parameterized by $\boldsymbol{\theta}$ with adaptive routing policy $\pi$, we minimize expected task loss subject to multidimensional hardware constraints:$$\min_{\pi} \; \mathbb{E}_{x \sim \mathcal{D}} \left[ \mathcal{L}_{\text{task}}(x; \boldsymbol{\theta}, \pi) \right] \quad \text{subject to} \quad \mathbb{E}_{x \sim \mathcal{D}} \left[ \mathcal{C}_k(x; \pi) \right] \le \mathcal{B}_k, \quad \forall k \in \mathcal{K}$$where $\mathcal{K} = \{\text{latency}, \text{memory}, \text{energy}, \text{bandwidth}\}$ and $\mathcal{B}_k$ represents the hardware SLA budget ceiling.Through Lagrangian duality, the unconstrained saddle-point objective is:$$\mathcal{L}(\boldsymbol{\theta}, \pi, \boldsymbol{\lambda}) = \mathbb{E}_{x \sim \mathcal{D}} \left[ \mathcal{L}_{\text{task}}(x; \boldsymbol{\theta}, \pi) \right] + \sum_{k \in \mathcal{K}} \lambda_k \left( \mathbb{E}_{x \sim \mathcal{D}} \left[ \mathcal{C}_k(x; \pi) \right] - \mathcal{B}_k \right)$$where $\boldsymbol{\lambda} = [\lambda_m, \lambda_e, \lambda_b]^T$ are Karush-Kuhn-Tucker (KKT) dual multipliers.### 2. Closed-Form Marginal Information-to-Cost AllocatorAt generation step $t$, given the token information state $\mathbf{z}_t$, the allocator selects an operational action $a = (r_t, \text{attn}_t, d_t, \text{kv}_t)$ that maximizes the **Marginal Utility Ratio**:$$\text{Value}(a \mid \mathbf{z}_t) = \frac{\widehat{\Delta Q}(a \mid \mathbf{z}_t)}{\Delta \mathcal{C}_{\text{latency}}(a) + \lambda_m \Delta \mathcal{C}_{\text{memory}}(a) + \lambda_e \Delta \mathcal{C}_{\text{energy}}(a) + \lambda_b \Delta \mathcal{C}_{\text{bandwidth}}(a) + \epsilon}$$The model does not merely ask *"How complex is this token?"* It solves:> **"Given what is known about this token ($\mathbf{z}_t$), the current model state, the remaining KV capacity, and the measured hardware profile, what is the cheapest additional computation that yields the greatest expected marginal improvement?"**---## 📐 Architecture Overview```mermaidgraph TDIn[Input Sequence x_1 ... x_t] --> Info[1. Token Information State Generator z_t in R^8]Info --> Alloc[2. Information-Value Resource Allocator]Cost[3. Hardware-Aware Cost Profiler] --> AllocAlloc --> Engine[4. Joint Hybrid Execution Engine]subgraph Execution PathsEngine --> TT[Nested TT Linear Cores: r in {1, 2, 4, 8}]Engine --> Attn[Attention: Classical Fast-SDPA vs QKSAM VQC]Engine --> KV[Adaptive KV Cache: FP16 / INT8 / INT4 / Evict]Engine --> QB[Quantum Backend: Classical Surrogate vs Sim]end```---## 🧮 Mathematical Formulations### 1. 8-Dimensional Token Information State ($\mathbf{z}_t$)At each autoregressive step $t$, the system constructs a normalized continuous state vector:$$\mathbf{z}_t = \begin{bmatrix} S_t & H_t & U_t & A_t & R_t & L_t & M_t & B_t \end{bmatrix}^T \in [0, 1]^8$$Each coordinate mathematically quantifies a distinct information-theoretic or hardware dimension:1. **Attention Dispersion / Cross-Head Entropy ($S_t$)**:$$S_t = -\frac{1}{N_h \ln t} \sum_{h=1}^{N_h} \sum_{j=1}^t \alpha_{h,t,j} \ln \alpha_{h,t,j}$$where $\alpha_{h,t,j}$ denotes the attention weight from query $t$ to key $j$ in head $h$.2. **Predictive Logit Entropy ($H_t$)**:$$H_t = -\frac{1}{\ln |V|} \sum_{v=1}^{|V|} p_t(v) \ln p_t(v), \quad p_t = \text{softmax}(\mathbf{y}_t)$$3. **Epistemic Token Uncertainty ($U_t$)**:$$U_t = 1 - \max_{v \in V} p_t(v)$$4. **Query Attention Importance Mass ($A_t$)**:$$A_t = \min \left(1, \; \frac{1}{N_h} \sum_{h=1}^{N_h} \frac{\|\mathbf{q}_{h,t}\|_2}{\sqrt{d_k}} \right)$$5. **Tensor-Train Approximation Residual ($R_t$)**:$$R_t = \frac{\|\mathbf{x}_t - \mathbf{x}_t^{(r)}\|_2}{\|\mathbf{x}_t\|_2 + \epsilon}$$6. **Latency Budget Pressure ($L_t$)**:$$L_t = \text{clip}\left( \frac{\tau_{\text{measured}}}{\tau_{\text{SLA}}}, \; 0, \; 1 \right)$$7. **KV-Cache Memory Capacity Pressure ($M_t$)**:$$M_t = \frac{\text{Tokens}_{\text{cached}}}{\text{Capacity}_{\text{max}}}$$8. **Memory Bus Traffic / Bandwidth Saturation ($B_t$)**:$$B_t = \text{clip}\left( \frac{\text{Bytes}_{\text{read}} + \text{Bytes}_{\text{written}}}{\text{PeakBandwidth} \times \Delta t}, \; 0, \; 1 \right)$$---### 2. Nested Tensor-Train Factorization & Zero-SVD SlicingDense linear transformations $\mathbf{W} \in \mathbb{R}^{D_{\text{out}} \times D_{\text{in}}}$ are factorized into $d$ connected tensor cores:$$\mathbf{W}(i_1 i_2 \dots i_d, \; o_1 o_2 \dots o_d) = \sum_{\alpha_0=1}^{r_0} \sum_{\alpha_1=1}^{r_1} \dots \sum_{\alpha_d=1}^{r_d} \prod_{k=1}^d \mathcal{G}^{(k)}_{\alpha_{k-1}, \; o_k, \; i_k, \; \alpha_k}, \quad r_0 = r_d = 1$$where $D_{\text{in}} = \prod_{k=1}^d i_k$ and $D_{\text{out}} = \prod_{k=1}^d o_k$.#### Instantaneous Nested SlicingUnlike legacy methods requiring $\mathcal{O}(d \cdot n^3)$ runtime Singular Value Decompositions (SVD) to truncate ranks, Q-TensorFormer pre-allocates nested cores at maximum bond dimension $r_{\max}=8$. For active rank $r \in \{1, 2, 4, 8\}$, the core is sliced instantaneously via zero-copy stride indexing:$$\mathcal{G}^{(k)}_{\text{active}}(r) = \mathcal{G}^{(k)}\left[ 1:\min(r, r_{k-1}), \; :, \; :, \; 1:\min(r, r_k) \right]$$$$\text{Runtime Overhead}: \; 0.00 \; \text{ms} \quad (\text{Pointer Striding, Zero SVD FLOPs})$$Active parameter complexity scales as:$$\mathcal{P}(r) = \sum_{k=1}^d r_{k-1}(r) \cdot o_k \cdot i_k \cdot r_k(r) \ll D_{\text{in}} \times D_{\text{out}}$$---### 3. Quantum Kernel Self-Attention (QKSAM)For ambiguous or high-entropy tokens ($U_t > 0.75$), attention is computed in an expanded $2^n$-dimensional quantum Hilbert space $\mathcal{H}$:$$|\phi(\mathbf{x})\rangle = \mathcal{U}_{\text{ansatz}}(\mathbf{x}) |0^{\otimes n}\rangle = \prod_{l=1}^L \left( \prod_{j=1}^n R_y\left(x_j^{(l)}\right) \prod_{j=1}^{n-1} \text{CNOT}_{j, j+1} \right) |0^{\otimes n}\rangle$$The attention kernel is the exact quantum state fidelity:$$K(\mathbf{q}_t, \mathbf{k}_j) = \left| \langle \phi(\mathbf{q}_t) \mid \phi(\mathbf{k}_j) \rangle \right|^2 = \text{Tr}\left[ \rho(\mathbf{q}_t) \rho(\mathbf{k}_j) \right]$$For standard tokens, the system executes classical Flash-SDPA:$$\text{Attn}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\left( \frac{\mathbf{Q}\mathbf{K}^T}{\sqrt{d_k}} \odot \mathbf{M} \right) \mathbf{V}$$---### 4. Adaptive KV Cache Quantization & Attention-Sink EvictionKV tensors $\mathbf{X} \in \{\mathbf{K}, \mathbf{V}\}$ transition dynamically across numerical precisions based on memory pressure $M_t$:* **Symmetric Channel-Wise INT8**:$$\hat{\mathbf{X}}_{\text{INT8}} = \text{clamp}\left( \left\lfloor \frac{\mathbf{X}}{s_8} \right\rceil, \; -128, \; 127 \right) \cdot s_8, \quad s_8 = \frac{\max |\mathbf{X}|}{127}$$* **Asymmetric Group-Wise INT4**:$$\hat{\mathbf{X}}_{\text{INT4}} = \left( \text{clamp}\left( \left\lfloor \frac{\mathbf{X} - z_4}{s_4} \right\rceil, \; 0, \; 15 \right) \cdot s_4 \right) + z_4$$$$s_4 = \frac{\max(\mathbf{X}) - \min(\mathbf{X})}{15}, \quad z_4 = \min(\mathbf{X})$$* **Attention-Sink Dynamic Eviction**:When context exceeds memory budget $\mathcal{B}_{\text{mem}}$, the retained token set $\mathcal{S}_{\text{retain}}$ preserves initial prompt sinks plus top attention earners:$$\mathcal{S}_{\text{retain}} = \mathcal{K}_{\text{sink}} \;\cup\; \underset{j \notin \mathcal{K}_{\text{sink}}}{\text{argtop}_K} \left( \sum_{h=1}^{N_h} \sum_{i=1}^t \alpha_{h, i, j} \right), \quad |\mathcal{K}_{\text{sink}}| = 4$$---### 5. Routing Stability via Hysteresis Anti-ChatteringTo eliminate destructive high-frequency route oscillation (chattering) between adjacent token ranks, the allocator updates action $a_t$ according to a dual-threshold hysteresis function:$$a_t = \begin{cases} a^*_t, & \text{if } \text{Value}(a^*_t \mid \mathbf{z}_t) - \text{Value}(a_{t-1} \mid \mathbf{z}_t) \ge \tau_{\text{hyst}} \;\land\; (t - t_{\text{last}}) \ge \delta_{\text{cooldown}} \\ a_{t-1}, & \text{otherwise} \end{cases}$$where $\tau_{\text{hyst}} = 0.15$ and $\delta_{\text{cooldown}} = 2$ tokens. This stabilization reduces routing churn by **81.4%**, eliminating tail latency spikes.---## 📊 Standardized Comparative Benchmark*All metrics rigorously classified as **MEASURED** (empirical hardware profiling), **ESTIMATED** (calibrated model), or **PROJECTED** (analytical scaling).*10 unmodified lines---## 🚀 Quick Start: Hugging Face IntegrationQ-TensorFormer is fully integrated into the Hugging Face `transformers` ecosystem:```pythonfrom transformers import AutoConfig, AutoModelForCausalLMimport src # Registers "qtensorformer"# 1. Load configuration and model directlyconfig = AutoConfig.from_pretrained("Premchan369/Q-TensorFormer")model = AutoModelForCausalLM.from_pretrained("Premchan369/Q-TensorFormer")# 2. Select a deployment preset# Options: "full", "balanced", "latency", "memory", "energy", "edge", "classical_only"model.set_preset("balanced")# 3. Autoregressive Generation with Adaptive KV Cache7 unmodified lines## 🧪 Reproducible Research ExperimentsAll empirical claims are verifiable via standalone one-command runners:```bash# 1. Standardized Baselines Comparison (Table 1)
README.md+141-71