πŸ”₯ Quantized Model: SmolLM-135M_gptq_g32_4bit πŸ”₯

This is a 4-bit quantized version of HuggingFaceTB/SmolLM-135M model, quantized by ConfidentialMind.com πŸ€–βœ¨
It leverages the open-source GPTQModel quantization to achieve 4-bit precision with a group size of 128 resulting in a smaller, faster model with minimal performance degradation.

Ran on a single NVIDIA A100 GPU with 80GB of VRAM.

Note batch_size is set quite high as the model is small, you may need to adjust this to your GPU VRAM.

Model Details

  • Original Model: HuggingFaceTB/SmolLM-135M
  • Quantized Model: SmolLM-135M_gptq_g32_4bit (this repository)
  • Quantization Method: GPTQ (4-bit, group size 128)
  • Quantization Library: GPTQModel
  • Calibration Dataset: wikitext/wikitext-2-raw-v1 (using 512 samples with seq len 4096)
  • Quantized by: ConfidentialMind.com

Usage

from gptqmodel import GPTQModel
from transformers import AutoTokenizer

# Use the local directory or JustJaro/SmolLM-135M_gptq_g32_4bit after upload
quantized_model_id = "/home/jarouljanov/models/quantized/SmolLM-135M_gptq_g32_4bit"  # or "JustJaro/SmolLM-135M_gptq_g32_4bit"
tokenizer = AutoTokenizer.from_pretrained(quantized_model_id)
model = GPTQModel.load(quantized_model_id, device="cuda:0")  # or "cpu"

input_text = "This is a test prompt"
inputs = tokenizer(input_text, return_tensors="pt").to("cuda:0")
outputs = model.generate(**inputs)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

Package Versions and Installation Instructions

See pyproject.toml for the exact UV project file. See the GPTQModel repo for more details. on how to install the package.

Use the provided pyproject.toml:

uv venv
source venv/bin/activate
uv sync

Environment Variables

HF_TOKEN=<YOUR_HF_TOKEN>
TOKENIZERS_PARALLELISM="true"
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

Quantization Script

Below is the exact quantize.py script used to generate this model (with the exact versions of the dependencies):

#!/usr/bin/env python3
"""
This script loads a source Hugging Face model and a calibration dataset,
quantizes the model using GPTQModel (with 4-bit precision and group size 128),
saves the quantized model using the Transformers API with safetensors (safe serialization)
under ~/models/quantized/, and then creates/updates a Hugging Face repository (with the
_gptq_g128_4bit suffix) by uploading the model, tokenizer, and an auto-generated README.md.

Usage example:
    python quantize.py --source-model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \
                       --calibration-dataset wikitext/wikitext-2-raw-v1 \
                       --seq-len 1024 --nsamples 256 --hf-token <YOUR_HF_TOKEN>
"""

import os
import shutil
import subprocess
import math
from enum import Enum
from pathlib import Path
from typing import List, Union

import torch
import typer
from datasets import load_dataset
from dotenv import load_dotenv, find_dotenv
from gptqmodel import GPTQModel, QuantizeConfig
from huggingface_hub import HfApi
from transformers import AutoTokenizer, PreTrainedTokenizerBase

load_dotenv(find_dotenv())
HF_TOKEN = os.getenv("HF_TOKEN")

app = typer.Typer()


class GroupSize(str, Enum):
    accurate: int = 32
    balanced: int = 64
    fast: int = 128


def get_text_from_example(example: dict) -> str:
    """
    Returns text from a dataset example.
    If the example contains a "text" field, and it is nonempty, that text is used.
    Otherwise, if it has a "messages" field (a list of dicts with a "content" key),
    the function returns the concatenation of all non-empty message contents.
    """
    if "text" in example and example["text"]:
        return example["text"]
    elif "messages" in example:
        contents = [msg.get("content", "").strip() for msg in example["messages"]]
        return " ".join([s for s in contents if s])
    else:
        return ""


def get_calibration_dataset(
    tokenizer: PreTrainedTokenizerBase,
    nsamples: int,
    seqlen: int,
    calibration_dataset: str
) -> List[dict]:
    """
    Loads a calibration dataset from the Hugging Face Hub (or from a local file).
    It accepts datasets with a single "text" field (like wikitext)
    or with a "messages" field (as in the Neural Magic LLM Compression Calibration dataset).
    Only examples whose extracted text length is at least 'seqlen' are kept.
    Each chosen example is tokenized (with truncation up to 'seqlen') and returned as a dict.
    """
    ds = None
    try:
        # Attempt to load from HF Hub.
        try:
            if "/" in calibration_dataset:
                parts = calibration_dataset.split("/", 1)
                ds = load_dataset(parts[0], parts[1], split="train")
            else:
                ds = load_dataset(calibration_dataset, split="train")
        except Exception as e:
            print(f"Error loading dataset '{calibration_dataset}' via load_dataset: {e}")
            ds = load_dataset(calibration_dataset, split="train")
            print(f"Loaded calibration dataset from full remote path {calibration_dataset}.")

    except Exception as e:
        print(f"Error loading dataset '{calibration_dataset}' via load_dataset: {e}")
        # Fallback: if the supplied calibration_dataset is a local path, try to load it as JSON-lines.
        if os.path.exists(calibration_dataset):
            try:
                ds = load_dataset("json", data_files=calibration_dataset, split="train")
                print(f"Loaded calibration dataset from local file {calibration_dataset}.")
            except Exception as e2:
                print(f"Error loading local json dataset from '{calibration_dataset}': {e2}")
                return []
        else:
            return []

    print(f"Dataset features: {ds.features}")

    # Filter examples that have at least 80% 'seqlen' of extracted text (wikitext-2-raw-v1 dataset has short examples).
    ds = ds.filter(lambda x: len(get_text_from_example(x)) <= int(seqlen * 0.8))
    sample_range = min(nsamples, len(ds))
    calibration_data = []
    for i in range(sample_range):
        example = ds[i]
        text = get_text_from_example(example)
        tokenized = tokenizer(text, truncation=True, max_length=seqlen, return_tensors="pt")
        tokenized = {k: v.squeeze(0) for k, v in tokenized.items()}
        calibration_data.append(tokenized)
    return calibration_data


def calculate_perplexity_manual(model, tokenizer, dataset_name="wikitext", dataset_config="wikitext-2-raw-v1", 
                               split="test", max_samples=100, max_length=512) -> Union[float, str]:
    """
    Calculate perplexity manually using a dataset.
    Based on the research from GPTQModel documentation.
    """
    try:
        # Load test dataset
        if "/" in dataset_name:
            dataset = load_dataset(dataset_name, split=split)
        else:
            dataset = load_dataset(dataset_name, dataset_config, split=split)
        
        # Filter out empty texts
        texts = [text for text in dataset["text"] if text.strip()]
        
        # Limit samples for efficiency
        texts = texts[:max_samples]
        
        typer.echo(f"Calculating perplexity on {len(texts)} samples from {dataset_name}...")
        
        model.model.eval()
        total_loss = 0.0
        total_tokens = 0
        
        with torch.no_grad():
            for i, text in enumerate(texts):
                if i % 20 == 0:
                    typer.echo(f"Processing sample {i+1}/{len(texts)}")
                
                # Tokenize the text
                inputs = tokenizer(
                    text,
                    return_tensors="pt",
                    truncation=True,
                    max_length=max_length,
                    padding=False
                )
                
                input_ids = inputs.input_ids.to(model.model.device)
                
                # Skip if too short
                if input_ids.size(1) < 2:
                    continue
                
                # Calculate loss
                outputs = model.model(input_ids, labels=input_ids)
                loss = outputs.loss
                
                # Accumulate loss and token count
                total_loss += loss.item() * input_ids.size(1)
                total_tokens += input_ids.size(1)
        
        if total_tokens == 0:
            return "N/A (No valid tokens processed)"
        
        # Calculate perplexity
        avg_loss = total_loss / total_tokens
        perplexity = math.exp(avg_loss)
        
        return perplexity
        
    except Exception as e:
        typer.echo(f"Error calculating perplexity manually: {e}")
        return f"N/A (Error: {str(e)})"


def calculate_perplexity_lm_eval(model, tokenizer) -> Union[float, str]:
    """
    Calculate perplexity using lm-eval framework if available.
    Based on GPTQModel documentation research.
    """
    try:
        from gptqmodel.utils.eval import EVAL
        
        # Try to use GPTQModel's built-in evaluation
        typer.echo("Attempting to calculate perplexity using GPTQModel.eval...")
        
        # Create a temporary directory to save the model for evaluation
        temp_model_path = "/tmp/temp_gptq_model"
        os.makedirs(temp_model_path, exist_ok=True)
        
        model.save_pretrained(temp_model_path)
        tokenizer.save_pretrained(temp_model_path)
        
        # Use GPTQModel.eval with lm-eval framework
        results = GPTQModel.eval(
            temp_model_path,
            framework=EVAL.LM_EVAL,
            tasks=["wikitext"],
            output_file=None
        )
        
        # Clean up temporary directory
        shutil.rmtree(temp_model_path, ignore_errors=True)
        
        # Extract perplexity from results
        if "wikitext" in results.get("results", {}):
            wikitext_results = results["results"]["wikitext"]
            if "perplexity" in wikitext_results:
                return wikitext_results["perplexity"]
        
        return "N/A (Perplexity not found in lm-eval results)"
        
    except ImportError:
        typer.echo("lm-eval framework not available, falling back to manual calculation")
        return None
    except Exception as e:
        typer.echo(f"Error using lm-eval: {e}, falling back to manual calculation")
        return None


def calculate_avg_ppl(model, tokenizer):
    """
    Computes the average perplexity using multiple methods.
    First tries lm-eval framework, then falls back to manual calculation.
    """
    typer.echo("Starting perplexity calculation...")
    
    # Method 1: Try lm-eval framework
    ppl_result = calculate_perplexity_lm_eval(model, tokenizer)
    if ppl_result is not None and not isinstance(ppl_result, str):
        typer.echo(f"βœ“ Perplexity calculated using lm-eval: {ppl_result:.4f}")
        return ppl_result
    
    # Method 2: Manual calculation
    typer.echo("Using manual perplexity calculation...")
    ppl_result = calculate_perplexity_manual(model, tokenizer)
    
    if isinstance(ppl_result, float):
        typer.echo(f"βœ“ Perplexity calculated manually: {ppl_result:.4f}")
        return ppl_result
    else:
        typer.echo(f"⚠ Perplexity calculation failed: {ppl_result}")
        return ppl_result


def get_pinned_package_versions():
    """
    Retrieves pinned package versions using 'uv pip freeze'.
    Returns a dictionary mapping lowercased package names to their versions.
    """
    try:
        result = subprocess.run(["uv", "pip", "freeze"], capture_output=True, text=True, check=True)
        packages_output = result.stdout.strip()
        versions = {}
        for line in packages_output.splitlines():
            if "==" in line:
                package_name, package_version = line.split("==", 1)
                versions[package_name.lower()] = package_version
        return versions
    except subprocess.CalledProcessError as e:
        typer.echo(f"Error running 'uv pip freeze': {e}", err=True)
        return {}
    except FileNotFoundError:
        typer.echo("uv command not found. Make sure uv is installed and in your PATH.", err=True)
        return {}


def self_read_script():
    """
    Reads the current script file content for inclusion in README.
    """
    try:
        script_path = os.path.abspath(__file__)
        with open(script_path, "r") as f:
            script_content = f.read()
    except Exception as e:
        script_content = "Error reading script content: " + str(e)
    return script_content


def get_my_user(hf_token):
    """
    Gets the Hugging Face username from the provided token.
    """
    api = HfApi(token=hf_token)
    user_info = api.whoami()
    try:
        username = user_info.get("name") or user_info.get("username")
    except Exception as e:
        typer.echo(f"Error retrieving username from Hugging Face API: {e}. Using default username.")
        username = api.whoami()
    if not username:
        typer.echo("Could not determine your Hugging Face username from the token, defaulting to hard coded username.",
                   err=True)
        username = "JustJaro"
    return username


def generate_readme(calibration_dataset, nsamples, quantized_model_dir,
                    quantized_model_name, script_content, seq_len, source_model, username, avg_ppl):
    """
    Generates a comprehensive README.md file for the quantized model.
    """
    # Format perplexity value for display
    if isinstance(avg_ppl, float):
        ppl_display = f"{avg_ppl:.4f}"
    else:
        ppl_display = str(avg_ppl)
    
    readme_content = f"""---
tags:
- gptq
- quantization
- 4bit
- confidentialmind
- text-generation
- apache2.0
- mistral-small-24b
---
# πŸ”₯ Quantized Model: {quantized_model_name} πŸ”₯

This is a 4-bit quantized version of [{source_model}](https://huggingface.co/{source_model}) model, quantized by [ConfidentialMind.com](https://www.confidentialmind.com) πŸ€–βœ¨  
It leverages the open-source GPTQModel quantization to achieve 4-bit precision with a group size of 128 resulting in a 
smaller, 
faster model with minimal performance degradation.

Ran on a single NVIDIA A100 GPU with 80GB of VRAM.

*Note* `batch_size` is set quite high as the model is small, you may need to adjust this to your GPU VRAM.

## Model Details
- **Original Model:** [{source_model}](https://huggingface.co/{source_model})
- **Quantized Model:** {quantized_model_name} (this repository)
- **Quantization Method:** GPTQ (4-bit, group size 128)
- **Quantization Library:** [GPTQModel](https://github.com/ModelCloud/GPTQModel/tree/main)
- **Calibration Dataset:** {calibration_dataset} (using {nsamples} samples with seq len {seq_len})
- **Quantized by:** [ConfidentialMind.com](https://www.confidentialmind.com)

## Usage

```python
from gptqmodel import GPTQModel
from transformers import AutoTokenizer

# Use the local directory or {username}/{quantized_model_name} after upload
quantized_model_id = "{quantized_model_dir}"  # or "{username}/{quantized_model_name}"
tokenizer = AutoTokenizer.from_pretrained(quantized_model_id)
model = GPTQModel.load(quantized_model_id, device="cuda:0")  # or "cpu"

input_text = "This is a test prompt"
inputs = tokenizer(input_text, return_tensors="pt").to("cuda:0")
outputs = model.generate(**inputs)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

Package Versions and Installation Instructions

See pyproject.toml for the exact UV project file. See the GPTQModel repo for more details. on how to install the package.

Use the provided pyproject.toml:

uv venv
source venv/bin/activate
uv sync

Environment Variables

HF_TOKEN=<YOUR_HF_TOKEN>
TOKENIZERS_PARALLELISM="true"
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

Quantization Script

Below is the exact quantize.py script used to generate this model (with the exact versions of the dependencies):

{script_content}

Quantization Performance

Average perplexity (PPL) on WikiText-2 test dataset: {ppl_display}

Perplexity calculated using {'GPTQModel evaluation framework' if isinstance(avg_ppl, float) else 'manual calculation method'}

Disclaimer

This model is for research purposes only. It may inherit limitations and biases from the original model and the quantization process. Please use responsibly and refer to the original model card for more details.

Contact

For any questions or support, please visit ConfidentialMind.com or contact us directly.

License

This model inherits the license from the original model. Please refer to the original model card for more details. Original model card: {source_model}

Author

This model was quantized by Jaro

Acknowledgements

Quantization performed using the GPTQModel pipeline.

TODO: Add gptqmodel.utils.eval integration and auto-generation of eval table.


Generated and quantized using GPTQModel.

Downloads last month
4
Safetensors
Model size
45.5M params
Tensor type
I32
Β·
BF16
Β·
F16
Β·
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support