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
Premchandyadav369 commited on
Commit ·
de00a85
1
Parent(s): 72bef29
fix(space): sync spaces.GPU ZeroGPU integration and 6.30.0 SDK
Browse files- SPACE_README.md +18 -11
- app.py +76 -55
SPACE_README.md
CHANGED
|
@@ -4,23 +4,30 @@ emoji: ⚛️
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: apache-2.0
|
| 11 |
-
short_description: Information-Value Adaptive
|
| 12 |
---
|
| 13 |
|
| 14 |
# ⚛️ Q-TensorFormer: Interactive Showcase
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
- **Technical Documentation:** https://premchan369.github.io/Q-TensorFormer/
|
| 20 |
-
- **Author:** Premchand Yadav
|
| 21 |
-
- **License:** Apache-2.0
|
| 22 |
|
| 23 |
-
###
|
| 24 |
-
1. **Live Dynamic Tensor-Train Slicing:**
|
| 25 |
-
2. **
|
| 26 |
-
3. **
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.30.0
|
| 8 |
+
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
license: apache-2.0
|
| 12 |
+
short_description: Information-Value-Driven Adaptive Tensor-Network Transformer
|
| 13 |
---
|
| 14 |
|
| 15 |
# ⚛️ Q-TensorFormer: Interactive Showcase
|
| 16 |
|
| 17 |
+
[](https://premchan369.github.io/Q-TensorFormer/)
|
| 18 |
+
[](https://huggingface.co/Premchan369/Q-TensorFormer)
|
| 19 |
+
[](https://colab.research.google.com/github/Premchan369/Q-TensorFormer/blob/main/notebooks/quickstart.ipynb)
|
| 20 |
+
[](LICENSE)
|
| 21 |
+
[](https://huggingface.co/Premchan369/Q-TensorFormer)
|
| 22 |
|
| 23 |
+
Welcome to the live demonstration of **Q-TensorFormer**, an information-value-driven adaptive Transformer architecture developed by **Premchand Yadav**.
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
### What This Space Demonstrates:
|
| 26 |
+
1. **💬 Live Dynamic Tensor-Train Slicing:** Type any prompt to watch the model slice Tensor-Train rank cores ($r \in [1, 16]$) token-by-token based on marginal informational value and target energy budgets.
|
| 27 |
+
2. **🎨 Token Complexity Heatmap:** Visualizes which tokens required full matrix rank vs. lightweight edge rank.
|
| 28 |
+
3. **📊 Adaptive KV-Cache Telemetry:** Real-time DRAM footprint reduction (up to **93.36% memory saved**) using streaming attention-sink protection and INT8/INT4 quantization.
|
| 29 |
+
4. **👁️ Multimodal Vision Projection:** Tensor-train projected visual tokens.
|
| 30 |
+
5. **⚡ LLM Compression Studio:** Interactive parameter savings calculator for open-weight models (Llama-3, Qwen, Mistral).
|
| 31 |
+
|
| 32 |
+
- **Official Repository:** [https://huggingface.co/Premchan369/Q-TensorFormer](https://huggingface.co/Premchan369/Q-TensorFormer)
|
| 33 |
+
- **Technical Documentation Portal:** [https://premchan369.github.io/Q-TensorFormer/](https://premchan369.github.io/Q-TensorFormer/)
|
app.py
CHANGED
|
@@ -21,6 +21,18 @@ import torch
|
|
| 21 |
from configuration_qtensorformer import QTensorFormerConfig
|
| 22 |
from modeling_qtensorformer import QTensorFormerForCausalLM
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
try:
|
| 25 |
import gradio as gr
|
| 26 |
HAS_GRADIO = True
|
|
@@ -38,13 +50,13 @@ if tok_path.exists():
|
|
| 38 |
else:
|
| 39 |
TOKENIZER = QTensorFormerTokenizer()
|
| 40 |
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
trained_ckpt_path = Path(__file__).resolve().parent / "checkpoints" / "hf_canonical_trained"
|
| 44 |
|
| 45 |
if trained_ckpt_path.exists():
|
| 46 |
try:
|
| 47 |
-
MODEL = QTensorFormerForCausalLM.from_pretrained(str(trained_ckpt_path)).to(
|
| 48 |
CONFIG = MODEL.config
|
| 49 |
except Exception as e:
|
| 50 |
print(f"[app.py] Notice during checkpoint loading: {e}. Falling back to dynamic initialization.")
|
|
@@ -60,7 +72,7 @@ if trained_ckpt_path.exists():
|
|
| 60 |
attention_sink_size=4,
|
| 61 |
kv_cache_window_size=128,
|
| 62 |
)
|
| 63 |
-
MODEL = QTensorFormerForCausalLM(CONFIG).to(
|
| 64 |
else:
|
| 65 |
CONFIG = QTensorFormerConfig(
|
| 66 |
vocab_size=256,
|
|
@@ -74,64 +86,73 @@ else:
|
|
| 74 |
attention_sink_size=4,
|
| 75 |
kv_cache_window_size=128,
|
| 76 |
)
|
| 77 |
-
MODEL = QTensorFormerForCausalLM(CONFIG).to(
|
| 78 |
|
| 79 |
MODEL.eval()
|
| 80 |
|
| 81 |
|
|
|
|
| 82 |
def generate_with_telemetry(prompt: str, max_tokens: int = 64, temperature: float = 0.7, target_budget: float = 1.0):
|
| 83 |
if not prompt.strip():
|
| 84 |
yield "Please enter a valid text prompt.", "Rank 8 (Balanced)", "0.0 mJ", "0.0 tok/s", []
|
| 85 |
return
|
| 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 |
def mock_vision_qa(image, question: str):
|
|
@@ -174,7 +195,7 @@ def build_app():
|
|
| 174 |
.kpi-box { padding: 15px; border-radius: 8px; background: #f8fafc; border: 1px solid #e2e8f0; text-align: center; }
|
| 175 |
"""
|
| 176 |
|
| 177 |
-
with gr.Blocks(title="Q-TensorFormer: Closed-Loop Adaptive LLM"
|
| 178 |
gr.Markdown(
|
| 179 |
"""
|
| 180 |
# ⚛️ Q-TensorFormer: Closed-Loop Information-Adaptive LLM
|
|
@@ -287,7 +308,7 @@ def build_app():
|
|
| 287 |
# Instantiate demo at module level for Hugging Face Spaces & Gradio discovery
|
| 288 |
demo = build_app()
|
| 289 |
|
| 290 |
-
if __name__ == "__main__":
|
| 291 |
if demo is not None:
|
| 292 |
demo.queue().launch(server_name="0.0.0.0", server_port=7860)
|
| 293 |
|
|
|
|
| 21 |
from configuration_qtensorformer import QTensorFormerConfig
|
| 22 |
from modeling_qtensorformer import QTensorFormerForCausalLM
|
| 23 |
|
| 24 |
+
try:
|
| 25 |
+
import spaces
|
| 26 |
+
HAS_SPACES = True
|
| 27 |
+
except ImportError:
|
| 28 |
+
HAS_SPACES = False
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def gpu_decorator(fn):
|
| 32 |
+
if HAS_SPACES:
|
| 33 |
+
return spaces.GPU(fn)
|
| 34 |
+
return fn
|
| 35 |
+
|
| 36 |
try:
|
| 37 |
import gradio as gr
|
| 38 |
HAS_GRADIO = True
|
|
|
|
| 50 |
else:
|
| 51 |
TOKENIZER = QTensorFormerTokenizer()
|
| 52 |
|
| 53 |
+
# Initialize model on CPU for instant cold-start and ZeroGPU handshake safety
|
| 54 |
+
MODEL_DEVICE = "cpu"
|
| 55 |
trained_ckpt_path = Path(__file__).resolve().parent / "checkpoints" / "hf_canonical_trained"
|
| 56 |
|
| 57 |
if trained_ckpt_path.exists():
|
| 58 |
try:
|
| 59 |
+
MODEL = QTensorFormerForCausalLM.from_pretrained(str(trained_ckpt_path)).to(MODEL_DEVICE)
|
| 60 |
CONFIG = MODEL.config
|
| 61 |
except Exception as e:
|
| 62 |
print(f"[app.py] Notice during checkpoint loading: {e}. Falling back to dynamic initialization.")
|
|
|
|
| 72 |
attention_sink_size=4,
|
| 73 |
kv_cache_window_size=128,
|
| 74 |
)
|
| 75 |
+
MODEL = QTensorFormerForCausalLM(CONFIG).to(MODEL_DEVICE)
|
| 76 |
else:
|
| 77 |
CONFIG = QTensorFormerConfig(
|
| 78 |
vocab_size=256,
|
|
|
|
| 86 |
attention_sink_size=4,
|
| 87 |
kv_cache_window_size=128,
|
| 88 |
)
|
| 89 |
+
MODEL = QTensorFormerForCausalLM(CONFIG).to(MODEL_DEVICE)
|
| 90 |
|
| 91 |
MODEL.eval()
|
| 92 |
|
| 93 |
|
| 94 |
+
@gpu_decorator
|
| 95 |
def generate_with_telemetry(prompt: str, max_tokens: int = 64, temperature: float = 0.7, target_budget: float = 1.0):
|
| 96 |
if not prompt.strip():
|
| 97 |
yield "Please enter a valid text prompt.", "Rank 8 (Balanced)", "0.0 mJ", "0.0 tok/s", []
|
| 98 |
return
|
| 99 |
|
| 100 |
+
run_device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 101 |
+
try:
|
| 102 |
+
if run_device == "cuda":
|
| 103 |
+
MODEL.to("cuda")
|
| 104 |
+
|
| 105 |
+
# Update PID budget setpoint
|
| 106 |
+
MODEL.model.pid_controller.target_budget = target_budget
|
| 107 |
+
MODEL.model.pid_controller.reset_state()
|
| 108 |
+
|
| 109 |
+
# Encode with deterministic QTensorFormerTokenizer
|
| 110 |
+
tokens = TOKENIZER.encode(prompt)
|
| 111 |
+
if not tokens:
|
| 112 |
+
tokens = [TOKENIZER.bos_id]
|
| 113 |
+
curr_ids = torch.tensor([tokens], dtype=torch.long, device=run_device)
|
| 114 |
+
|
| 115 |
+
generated_text = prompt
|
| 116 |
+
token_ranks = []
|
| 117 |
+
past_key_values = None
|
| 118 |
+
|
| 119 |
+
t0 = time.perf_counter()
|
| 120 |
+
|
| 121 |
+
for step in range(max_tokens):
|
| 122 |
+
with torch.no_grad():
|
| 123 |
+
model_in = curr_ids if step == 0 else curr_ids[:, -1:]
|
| 124 |
+
outputs = MODEL(model_in, past_key_values=past_key_values, use_cache=True)
|
| 125 |
+
logits = outputs.logits[:, -1, :]
|
| 126 |
+
past_key_values = outputs.past_key_values
|
| 127 |
+
|
| 128 |
+
if temperature > 0:
|
| 129 |
+
probs = torch.softmax(logits / max(1e-4, temperature), dim=-1)
|
| 130 |
+
next_tok = torch.multinomial(probs, num_samples=1)
|
| 131 |
+
else:
|
| 132 |
+
next_tok = logits.argmax(dim=-1, keepdim=True)
|
| 133 |
+
|
| 134 |
+
curr_ids = torch.cat([curr_ids, next_tok], dim=1)
|
| 135 |
+
tok_id = int(next_tok[0, 0].item())
|
| 136 |
+
tok_str = TOKENIZER.decode([tok_id])
|
| 137 |
+
generated_text += tok_str
|
| 138 |
+
|
| 139 |
+
# Read live controller rank
|
| 140 |
+
pid_ctrl = MODEL.model.pid_controller
|
| 141 |
+
active_rank = int(pid_ctrl.rank_levels[int(pid_ctrl.active_rank_idx.item())])
|
| 142 |
+
token_ranks.append((tok_str, f"Rank {active_rank}"))
|
| 143 |
+
|
| 144 |
+
elapsed = time.perf_counter() - t0
|
| 145 |
+
tok_per_sec = (step + 1) / max(1e-6, elapsed)
|
| 146 |
+
est_mj_per_tok = (active_rank / 16.0) * 1.8 + 0.4 # mJ estimate proportional to TT-rank
|
| 147 |
+
|
| 148 |
+
rank_display = f"Rank {active_rank} ({'Full' if active_rank == 16 else 'Compressed' if active_rank == 8 else 'Ultra-Edge'})"
|
| 149 |
+
energy_display = f"{est_mj_per_tok:.2f} mJ/tok"
|
| 150 |
+
speed_display = f"{tok_per_sec:.1f} tokens/sec"
|
| 151 |
+
|
| 152 |
+
yield generated_text, rank_display, energy_display, speed_display, token_ranks
|
| 153 |
+
finally:
|
| 154 |
+
if run_device == "cuda":
|
| 155 |
+
MODEL.to("cpu")
|
| 156 |
|
| 157 |
|
| 158 |
def mock_vision_qa(image, question: str):
|
|
|
|
| 195 |
.kpi-box { padding: 15px; border-radius: 8px; background: #f8fafc; border: 1px solid #e2e8f0; text-align: center; }
|
| 196 |
"""
|
| 197 |
|
| 198 |
+
with gr.Blocks(title="Q-TensorFormer: Closed-Loop Adaptive LLM") as demo:
|
| 199 |
gr.Markdown(
|
| 200 |
"""
|
| 201 |
# ⚛️ Q-TensorFormer: Closed-Loop Information-Adaptive LLM
|
|
|
|
| 308 |
# Instantiate demo at module level for Hugging Face Spaces & Gradio discovery
|
| 309 |
demo = build_app()
|
| 310 |
|
| 311 |
+
if __name__ == "__main__" or os.environ.get("SPACE_ID"):
|
| 312 |
if demo is not None:
|
| 313 |
demo.queue().launch(server_name="0.0.0.0", server_port=7860)
|
| 314 |
|