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 ·
de00a85
1
Parent(s): 72bef29
fix(space): sync spaces.GPU ZeroGPU integration and 6.30.0 SDK
Browse filesFiles changed (2)
- SPACE_README.md+18-11
- app.py+76-55
3 unmodified lines4567789101111121314151616171819202122181920212324232425262526272829303132333 unmodified linescolorFrom: indigocolorTo: purplesdk: gradiosdk_version: 4.44.0sdk_version: 6.30.0python_version: '3.12'app_file: app.pypinned: falselicense: apache-2.0short_description: Information-Value Adaptive Transformer with live rank slicing & telemetryshort_description: Information-Value-Driven Adaptive Tensor-Network Transformer---
# ⚛️ Q-TensorFormer: Interactive Showcase
Interactive demonstration of **Q-TensorFormer**, an information-value-driven adaptive Transformer architecture.[](https://premchan369.github.io/Q-TensorFormer/)[](https://huggingface.co/Premchan369/Q-TensorFormer)[](https://colab.research.google.com/github/Premchan369/Q-TensorFormer/blob/main/notebooks/quickstart.ipynb)[](LICENSE)[](https://huggingface.co/Premchan369/Q-TensorFormer)
- **Canonical Model Hub:** https://huggingface.co/Premchan369/Q-TensorFormer- **Technical Documentation:** https://premchan369.github.io/Q-TensorFormer/- **Author:** Premchand Yadav- **License:** Apache-2.0Welcome to the live demonstration of **Q-TensorFormer**, an information-value-driven adaptive Transformer architecture developed by **Premchand Yadav**.
### Features in this Space:1. **Live Dynamic Tensor-Train Slicing:** Observe token-by-token active rank adjustments ($r \in [1, 16]$) based on token complexity and device pressure.2. **Adaptive KV Cache Telemetry:** Inspect real-time memory savings with attention-sink preservation and INT8/INT4 quantization.3. **Closed-Loop PID Control:** Adjust target energy budgets and watch shadow prices regulate computational capacity in real time.### What This Space Demonstrates: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.2. **🎨 Token Complexity Heatmap:** Visualizes which tokens required full matrix rank vs. lightweight edge rank.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.4. **👁️ Multimodal Vision Projection:** Tensor-train projected visual tokens.5. **⚡ LLM Compression Studio:** Interactive parameter savings calculator for open-weight models (Llama-3, Qwen, Mistral).
- **Official Repository:** [https://huggingface.co/Premchan369/Q-TensorFormer](https://huggingface.co/Premchan369/Q-TensorFormer)- **Technical Documentation Portal:** [https://premchan369.github.io/Q-TensorFormer/](https://premchan369.github.io/Q-TensorFormer/)20 unmodified lines21222324252627282930313233343536373811 unmodified lines505152414253545556575847596061629 unmodified lines72737463757677787 unmodified lines8687887789909192939495969798991001011021031048788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715836 unmodified lines195196197177198199200201106 unmodified lines30830931029031131231331420 unmodified linesfrom configuration_qtensorformer import QTensorFormerConfigfrom modeling_qtensorformer import QTensorFormerForCausalLM
try: import spaces HAS_SPACES = Trueexcept ImportError: HAS_SPACES = False
def gpu_decorator(fn): if HAS_SPACES: return spaces.GPU(fn) return fn
try: import gradio as gr HAS_GRADIO = True11 unmodified lineselse: TOKENIZER = QTensorFormerTokenizer()
# Load trained canonical checkpoint if present, with graceful fallbackDEVICE = "cuda" if torch.cuda.is_available() else "cpu"# Initialize model on CPU for instant cold-start and ZeroGPU handshake safetyMODEL_DEVICE = "cpu"trained_ckpt_path = Path(__file__).resolve().parent / "checkpoints" / "hf_canonical_trained"
if trained_ckpt_path.exists(): try: MODEL = QTensorFormerForCausalLM.from_pretrained(str(trained_ckpt_path)).to(DEVICE) MODEL = QTensorFormerForCausalLM.from_pretrained(str(trained_ckpt_path)).to(MODEL_DEVICE) CONFIG = MODEL.config except Exception as e: print(f"[app.py] Notice during checkpoint loading: {e}. Falling back to dynamic initialization.")9 unmodified lines attention_sink_size=4, kv_cache_window_size=128, ) MODEL = QTensorFormerForCausalLM(CONFIG).to(DEVICE) MODEL = QTensorFormerForCausalLM(CONFIG).to(MODEL_DEVICE)else: CONFIG = QTensorFormerConfig( vocab_size=256,7 unmodified lines attention_sink_size=4, kv_cache_window_size=128, ) MODEL = QTensorFormerForCausalLM(CONFIG).to(DEVICE) MODEL = QTensorFormerForCausalLM(CONFIG).to(MODEL_DEVICE)
MODEL.eval()
@gpu_decoratordef generate_with_telemetry(prompt: str, max_tokens: int = 64, temperature: float = 0.7, target_budget: float = 1.0): if not prompt.strip(): yield "Please enter a valid text prompt.", "Rank 8 (Balanced)", "0.0 mJ", "0.0 tok/s", [] return
run_device = "cuda" if torch.cuda.is_available() else "cpu" try: if run_device == "cuda": MODEL.to("cuda")
# Update PID budget setpoint MODEL.model.pid_controller.target_budget = target_budget MODEL.model.pid_controller.reset_state()
# Encode with deterministic QTensorFormerTokenizer tokens = TOKENIZER.encode(prompt) if not tokens: tokens = [TOKENIZER.bos_id] curr_ids = torch.tensor([tokens], dtype=torch.long, device=DEVICE)
generated_text = prompt token_ranks = [] past_key_values = None
t0 = time.perf_counter()
for step in range(max_tokens): with torch.no_grad(): model_in = curr_ids if step == 0 else curr_ids[:, -1:] outputs = MODEL(model_in, past_key_values=past_key_values, use_cache=True) logits = outputs.logits[:, -1, :] past_key_values = outputs.past_key_values
if temperature > 0: probs = torch.softmax(logits / max(1e-4, temperature), dim=-1) next_tok = torch.multinomial(probs, num_samples=1) else: next_tok = logits.argmax(dim=-1, keepdim=True)
curr_ids = torch.cat([curr_ids, next_tok], dim=1) tok_id = int(next_tok[0, 0].item()) tok_str = TOKENIZER.decode([tok_id]) generated_text += tok_str
# Read live controller rank pid_ctrl = MODEL.model.pid_controller active_rank = int(pid_ctrl.rank_levels[int(pid_ctrl.active_rank_idx.item())]) token_ranks.append((tok_str, f"Rank {active_rank}"))
elapsed = time.perf_counter() - t0 tok_per_sec = (step + 1) / max(1e-6, elapsed) est_mj_per_tok = (active_rank / 16.0) * 1.8 + 0.4 # mJ estimate proportional to TT-rank
rank_display = f"Rank {active_rank} ({'Full' if active_rank == 16 else 'Compressed' if active_rank == 8 else 'Ultra-Edge'})" energy_display = f"{est_mj_per_tok:.2f} mJ/tok" speed_display = f"{tok_per_sec:.1f} tokens/sec"
yield generated_text, rank_display, energy_display, speed_display, token_ranks # Update PID budget setpoint MODEL.model.pid_controller.target_budget = target_budget MODEL.model.pid_controller.reset_state()
# Encode with deterministic QTensorFormerTokenizer tokens = TOKENIZER.encode(prompt) if not tokens: tokens = [TOKENIZER.bos_id] curr_ids = torch.tensor([tokens], dtype=torch.long, device=run_device)
generated_text = prompt token_ranks = [] past_key_values = None
t0 = time.perf_counter()
for step in range(max_tokens): with torch.no_grad(): model_in = curr_ids if step == 0 else curr_ids[:, -1:] outputs = MODEL(model_in, past_key_values=past_key_values, use_cache=True) logits = outputs.logits[:, -1, :] past_key_values = outputs.past_key_values
if temperature > 0: probs = torch.softmax(logits / max(1e-4, temperature), dim=-1) next_tok = torch.multinomial(probs, num_samples=1) else: next_tok = logits.argmax(dim=-1, keepdim=True)
curr_ids = torch.cat([curr_ids, next_tok], dim=1) tok_id = int(next_tok[0, 0].item()) tok_str = TOKENIZER.decode([tok_id]) generated_text += tok_str
# Read live controller rank pid_ctrl = MODEL.model.pid_controller active_rank = int(pid_ctrl.rank_levels[int(pid_ctrl.active_rank_idx.item())]) token_ranks.append((tok_str, f"Rank {active_rank}"))
elapsed = time.perf_counter() - t0 tok_per_sec = (step + 1) / max(1e-6, elapsed) est_mj_per_tok = (active_rank / 16.0) * 1.8 + 0.4 # mJ estimate proportional to TT-rank
rank_display = f"Rank {active_rank} ({'Full' if active_rank == 16 else 'Compressed' if active_rank == 8 else 'Ultra-Edge'})" energy_display = f"{est_mj_per_tok:.2f} mJ/tok" speed_display = f"{tok_per_sec:.1f} tokens/sec"
yield generated_text, rank_display, energy_display, speed_display, token_ranks finally: if run_device == "cuda": MODEL.to("cpu")
def mock_vision_qa(image, question: str):36 unmodified lines .kpi-box { padding: 15px; border-radius: 8px; background: #f8fafc; border: 1px solid #e2e8f0; text-align: center; } """
with gr.Blocks(title="Q-TensorFormer: Closed-Loop Adaptive LLM", css=custom_css) as demo: with gr.Blocks(title="Q-TensorFormer: Closed-Loop Adaptive LLM") as demo: gr.Markdown( """ # ⚛️ Q-TensorFormer: Closed-Loop Information-Adaptive LLM106 unmodified lines# Instantiate demo at module level for Hugging Face Spaces & Gradio discoverydemo = build_app()
if __name__ == "__main__":if __name__ == "__main__" or os.environ.get("SPACE_ID"): if demo is not None: demo.queue().launch(server_name="0.0.0.0", server_port=7860)
SPACE_README.md+18-11
app.py+76-55