CoolFace
Apppublic

Sabithulla/lightweight-ai-backend

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
App README

Lightweight Multi-Model AI Backend for Hugging Face Spaces

Production-Ready for FREE CPU Tier

๐Ÿš€ Quick Start

This is a complete, production-ready Hugging Face Gradio Space optimized for the FREE CPU tier. It requires NO GPU and includes four AI capabilities:

โœ… General chat (powered by TinyLlama) โœ… Code generation (powered by TinyLlama) โœ… Text summarization (powered by FLAN-T5-Small) โœ… Text-to-image generation (lightweight procedural)

๐Ÿ“ฆ Features

Optimization for CPU Tier

  • โ€”Lazy Loading: Models loaded only when needed
  • โ€”Memory Efficient: ~1.5-2GB total RAM usage
  • โ€”Fast Responses: Token limits ensure <10s per request
  • โ€”Queue System: Handles concurrent requests safely
  • โ€”Float32 Precision: Optimized for CPU computation

Model Selection

FeatureModelSizeSpeed
ChatTinyLlama-1.1B-Chat-v1.01.1B paramsโšก Very Fast
CodeTinyLlama-1.1B-Chat-v1.01.1B paramsโšก Very Fast
Summarizationgoogle/flan-t5-small170M paramsโšกโšก Fastest
Image GenProcedural RenderingN/Aโšกโšกโšก Instant

API Endpoints

All endpoints are exposed through Gradio and accessible programmatically:

1. /generate_chat - General Chat
python
{
    "prompt": "Hello, how are you?",
    "max_tokens": 150,
    "temperature": 0.7
}
# Returns: Generated chat response
2. /generate_code - Code Generation
python
{
    "prompt": "Write a function to reverse a string",
    "max_tokens": 256,
    "temperature": 0.3
}
# Returns: Generated Python code
3. /summarize_text - Text Summarization
python
{
    "text": "Long article text here...",
    "max_length": 100
}
# Returns: Summarized text
4. /generate_image - Text-to-Image
python
{
    "prompt": "A red sunset over mountains",
    "width": 256,
    "height": 256
}
# Returns: Generated PIL Image

๐Ÿ”ง Configuration & Tuning

Model Parameters

Chat Generation:

  • โ€”max_tokens: 50-200 (default: 150)
  • โ€”temperature: 0.1-1.0 (default: 0.7)
  • โ€”top_p: Fixed at 0.9 for quality

Code Generation:

  • โ€”max_tokens: 100-300 (default: 256)
  • โ€”temperature: 0.1-1.0 (default: 0.3 - lower for deterministic code)

Summarization:

  • โ€”max_length: 20-150 (default: 100)
  • โ€”min_length: Fixed at 20

Image Generation:

  • โ€”width: 128-256 (default: 256)
  • โ€”height: 128-256 (default: 256)

Memory Optimization

The application includes several memory-saving techniques:

python
# 1. Lazy Loading
# Models only loaded when first called
model_manager.load_chat_model()  # Called only if needed

# 2. Garbage Collection
gc.collect()  # Called after each inference

# 3. CPU Optimization
torch.set_num_threads(4)  # Limits threading overhead

# 4. Token Limits
max_tokens = min(max_tokens, 200)  # Hard caps for stability

# 5. Input Truncation
if len(text) > 1000:
    text = text[:1000]  # Prevent OOM on summarization

๐Ÿ“Š Performance Benchmarks (Rough Estimates)

On a 2-core CPU with 4GB RAM:

OperationTimeRAM Used
Load TinyLlama8-12s1.2GB
Chat Response (50 tokens)3-5s1.2GB
Load FLAN-T54-6s0.5GB
Summarize (100 words)2-3s0.5GB
Generate Image (256x256)<1s<100MB

Total idle memory: ~1.5GB Max concurrent memory: ~2GB

๐Ÿš€ Deployment to Hugging Face Spaces

Step 1: Create New Space

  1. 1.Go to huggingface.co/spaces
  2. 2.Click "Create new Space"
  3. 3.Select "Gradio" as SDK
  4. 4.Choose "Public" or "Private"

Step 2: Upload Files

Upload these files to your Space:

  • โ€”app.py
  • โ€”requirements.txt
  • โ€”.gitignore (optional)

Step 3: Configure Space Settings

  • โ€”Docker: Leave as default (builds from requirements.txt)
  • โ€”Python requirements: Auto-detected from requirements.txt
  • โ€”Persistent storage: Not needed for this project

Space will auto-restart after upload. Models will be downloaded on first use.

๐Ÿ” Advanced Usage

Using the API Programmatically

python
import requests
import json

# Call the chat endpoint
response = requests.post(
    "https://your-username-ai-backend.hf.space/api/predict",
    json={
        "data": [
            "Hello, what is Python?",  # prompt
            150,                        # max_tokens
            0.7                         # temperature
        ]
    }
)

result = response.json()
print(result["data"][0])  # Generated response

Using with cURL

bash
curl -X POST https://your-username-ai-backend.hf.space/api/predict \
  -H "Content-Type: application/json" \
  -d '{
    "data": ["What is machine learning?", 150, 0.7]
  }'

Custom Model Loading

To use different models, modify the model names in app.py:

python
# In model_manager.load_chat_model():
model_name = "different/model-name"  # Change here

Recommended lightweight alternatives:

  • โ€”Chat: microsoft/phi-1, mosaicml/mpt-7b-instruct (7B, may be heavy)
  • โ€”Summarization: google/flan-t5-base (larger, ~250M)
  • โ€”Code: Same TinyLlama or try Salesforce/codet5-small

โš ๏ธ Troubleshooting

Out of Memory Errors

Symptom: Space crashes with OOM Solution:

  1. 1.Reduce max_tokens limits in code
  2. 2.Reduce max summarization input length
  3. 3.Increase queue timeout in demo.launch()

Slow Responses

Symptom: Takes >10 seconds per request Solution:

  1. 1.Reduce token limits
  2. 2.Disable some models in production
  3. 3.Monitor CPU/RAM in Space logs

Model Download Failures

Symptom: "Cannot download model" error Solution:

  1. 1.Check internet connectivity in logs
  2. 2.Models auto-download on first request (may take 1-2 min)
  3. 3.Wait for "Model loaded successfully" message

๐ŸŽฏ Production Checklist

  • โ€”โœ… Models tested on CPU
  • โ€”โœ… Error handling for all endpoints
  • โ€”โœ… Memory cleanup between requests
  • โ€”โœ… Queue system for concurrency
  • โ€”โœ… Token limits for stability
  • โ€”โœ… Float32 precision for CPU
  • โ€”โœ… Gradio Blocks UI for testing
  • โ€”โœ… API documentation
  • โ€”โœ… Lazy loading implemented
  • โ€”โœ… Optimized requirements.txt

๐Ÿ“ˆ Scaling Beyond Free Tier

If you need more performance:

  1. 1.Upgrade to paid GPU tier: Enables larger models (7B+)
  2. 2.Use external APIs: ollama, vLLM for local deployment
  3. 3.Implement caching: Cache popular responses
  4. 4.Model distillation: Train smaller task-specific models

๐Ÿ“ License & Attribution

  • โ€”TinyLlama: MIT License
  • โ€”FLAN-T5: Apache 2.0
  • โ€”Transformers: Apache 2.0
  • โ€”Gradio: Apache 2.0

๐Ÿค Contributing

To modify or improve:

  1. 1.Clone this Space locally
  2. 2.Modify app.py or requirements.txt
  3. 3.Test locally with python app.py
  4. 4.Push changes back to Space

๐Ÿ“ง Support

For issues:

  • โ€”Check Space logs (Settings โ†’ Logs)
  • โ€”Review "Troubleshooting" section above
  • โ€”Check Hugging Face Spaces documentation
  • โ€”Review model cards on huggingface.co

Built for Hugging Face Spaces - Optimized for FREE CPU Tier ๐Ÿš€

Created: 2024 Last Updated: 2024