🤖 AI/ML

GGUF

GGML Universal Format

A model format used by llama.cpp. Optimized for CPU inference.

📖 Detailed Explanation

GGUF (GGML Universal Format) is an LLM model storage format developed by the llama.cpp project, which replaced the previous GGML format in August 2023. It embeds metadata directly in the model file, so a model can be distributed as a single file, and its structure is optimized for CPU inference.

The key feature of GGUF is its extensible metadata system. The model architecture, tokenizer, quantization information, license and more are included in the file header, so a separate config.json or tokenizer file is not needed. Versioning and backward compatibility are also supported at the format level.

GGUF supports various quantization levels (Q2_K, Q3_K_M, Q4_K_M, Q5_K_M, Q6_K, Q8_0, etc.). For example, the Llama-2-7B model is 14GB in FP16, but it can be reduced to 4.1GB with Q4_K_M quantization, and the quality loss is less than about 0.5% in terms of perplexity.

In practice, GGUF has become the standard for local LLM deployment. Most local inference tools, such as Ollama, LM Studio, and Text Generation WebUI, support GGUF, and thousands of GGUF models converted by TheBloke and others are publicly available on Hugging Face. On M1/M2 Macs, Metal acceleration achieves an inference speed of 20-40 tokens per second.

💻 Code Example

# GGUF 모델 사용 예제 (llama-cpp-python)
from llama_cpp import Llama

# GGUF 모델 로드 (Q4_K_M 양자화)
llm = Llama(
    model_path="./models/llama-2-7b-chat.Q4_K_M.gguf",
    n_ctx=4096,          # 컨텍스트 길이
    n_threads=8,         # CPU 스레드 수
    n_gpu_layers=35,     # GPU 오프로드 레이어 수 (0=CPU only)
    verbose=False
)

# 텍스트 생성
output = llm(
    "Q: What is the capital of France? A:",
    max_tokens=50,
    temperature=0.7,
    top_p=0.9,
    stop=["Q:", "\n\n"]
)
print(output['choices'][0]['text'])

# 채팅 형식 사용
response = llm.create_chat_completion(
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    max_tokens=200
)
print(response['choices'][0]['message']['content'])

# ----------------------------------------
# Hugging Face에서 GGUF로 변환하기
# ----------------------------------------
# 터미널에서 실행:
# pip install llama-cpp-python[server]
# python -m llama_cpp.server --model ./model.gguf --host 0.0.0.0 --port 8000

# GGUF 변환 (llama.cpp 사용)
# 1. llama.cpp 클론 및 빌드
# git clone https://github.com/ggerganov/llama.cpp
# cd llama.cpp && make

# 2. HuggingFace 모델을 GGUF로 변환
# python convert-hf-to-gguf.py /path/to/hf-model --outfile model-f16.gguf

# 3. 양자화 적용
# ./quantize model-f16.gguf model-q4_k_m.gguf Q4_K_M

# ----------------------------------------
# Ollama로 GGUF 사용하기
# ----------------------------------------
# Modelfile 작성
modelfile_content = """
FROM ./llama-2-7b.Q4_K_M.gguf
TEMPLATE \"\"\"[INST] {{ .System }} {{ .Prompt }} [/INST]\"\"\"
SYSTEM \"You are a helpful AI assistant.\"
PARAMETER temperature 0.7
PARAMETER num_ctx 4096
"""

# 터미널에서:
# ollama create my-llama -f Modelfile
# ollama run my-llama "Hello, how are you?"

🗣️ Say It Like This in Practice

Technical Interview Scenario

"What is the difference between GGUF and safetensors?" - "safetensors is a PyTorch/JAX-compatible format optimized for GPU training and inference, while GGUF is specialized for CPU inference with llama.cpp. GGUF has the advantage of embedding quantization and metadata, so it can be distributed as a single file."

Project Meeting

"Which quantization would you recommend for running a 7B model on a local PC?" - "With 16GB of RAM, I recommend Q4_K_M. The file size is around 4GB, and there is almost no quality loss. With 8GB of RAM, you would have to use Q3_K_M or Q2_K, and in that case the quality degradation is noticeable. If you have a GPU, offloading some layers with n_gpu_layers makes it 2-3 times faster."

Code Review

"I raised n_ctx to 8192 but I'm running out of memory. What should I do?" - "As the context length increases, KV cache memory surges. At 8192, about 2-3GB of additional memory is needed. You can optimize memory usage by adjusting rope_freq_base to apply RoPE scaling, or by reducing n_batch."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Choosing a Quantization Level

With quantization below Q4_K_M, the quality degradation becomes noticeable in complex reasoning tasks. Q5_K_M or higher is recommended for coding and math problems, while Q3_K_M is sufficient for simple conversations.

2
Memory Calculation Caution

In addition to the model file size, additional memory is needed for the KV cache, inference buffers, and so on. In general, secure RAM of 1.5-2 times the model size. If you increase the context length, more is needed.

3
Source Verification Required

Many GGUF files on Hugging Face were converted by the community. Use models from trusted uploaders (TheBloke, bartowski, etc.) and verify the checksums.

🔗 Related Terms

📚 Learn More