NCM Sumé (Next-Concept Modeling in Portuguese)
NCM Sumé is an experimental adaptation and proof-of-concept of the Next-Concept Modeling (NCM) architecture, trained to follow instructions and converse in Brazilian Portuguese.
The model is named after Sumé, an ancestral figure in Tupi mythology associated with transmitting practical knowledge, agricultural techniques, and law to indigenous peoples.
🇧🇷 Nota em Português: A documentação completa em português está disponível no arquivo README_pt.md e na seção expansível ao final desta página.
1. Motivation and The 8 GB VRAM Constraint
Standard autoregressive language models generate text token by token. For a 300-word response, the GPU must perform 300 sequential forward passes, creating a structural latency bottleneck. The Next-Concept Modeling framework (introduced by Stanford's Hazy Research group) alters this mechanism: text is first drafted as high-level abstract concept codes, which are then refined in parallel across discrete hierarchical passes.
The question behind this project was simple:
Can we take the NCM architecture from scratch and train it within the constraints of a single consumer laptop GPU (an NVIDIA GeForce RTX 4060 Laptop GPU with 8 GB VRAM) to converse in Portuguese, similar to small quantized open models?
This repository documents the training pipeline, datasets, parameter counts, and benchmarks to serve as a reference for anyone exploring coarse-to-fine discrete text modeling on personal hardware.
2. Research Foundation and Attribution
This work is a community adaptation grounded in:
- Paper: "Next-Concept Modeling: Fast, Parallel Coarse-to-Fine Text Generation" (arXiv:2610.14162)
- Authors: Stanford Hazy Research Group (Hermann Kumbong et al.)
- Official Repository: https://github.com/HazyResearch/ncm
- Base Code License: MIT License
3. Training Data and Ingestion Strategy
To avoid exhausting local disk space (since raw code repositories easily exceed tens of gigabytes), data was ingested using memory streaming:
- BigCode StarCoder (
bigcode/starcoderdata):- Python slice: extracted standalone functions, algorithms, and classes with docstrings.
- Enforced strict 4-space indentation to preserve Python block structure.
- Everything Instruct Multilingual (
rombodawg/Everything_Instruct_Multilingual):- Portuguese slice (
pt): instructional prompt-response pairs focused on logic, explanations, and general conversation.
- Portuguese slice (
- Boakpe Historinhas (
Boakpe/historinhas):- ~6,000 short story samples in Brazilian Portuguese to reinforce vocabulary and grammatical cohesion.
- Teacher Distillation (Qwen 2.5 3B):
- Generated 1,500 instruction-response pairs locally to transfer conversational tone and empathetic response patterns to the NCM instruction format.
4. Architecture and Parameter Count
The system consists of two decoupled components:
A. Hierarchical Tokenizer (Residual VQ-VAE)
- Weight file size: 222 MB
- Parameter count: 36.43 million parameters
- Vocabulary: Custom BPE with 8,192 tokens (including Portuguese diacritics and Python syntax tokens).
- Residual Codebooks: 4 hierarchical abstraction levels:
- Level 1: Broad discourse intent and global topic outline.
- Level 2: Syntactic structure of phrases and code blocks.
- Level 3: Lexical subword refinements.
- Level 4: Surface tokens, accentuation, and punctuation.
B. Parallel Transformer Generator (NextConcept Transformer)
- Weight file size: 356 MB
- Parameter count: 88.61 million parameters
- Inference mechanism: Conditioned on the prompt context and decoded concept levels, it evaluates and predicts concept tokens in parallel per level, requiring only a small, fixed number of forward passes on the GPU.
Total System Parameters: approximately 125 million parameters (88.61M in the generator + 36.43M in the tokenizer).
5. Training Pipeline on 8 GB VRAM
The primary operational constraint was avoiding out-of-memory (OOM) errors on 8 GB of VRAM. Key implementation decisions included:
- Isolated Runtime: Docker container on WSL2 using
pytorch/pytorch:2.4.0-cuda12.4-cudnn9-runtime. - Native bfloat16 Precision:
torch.amp.autocast('cuda', dtype=torch.bfloat16)reduced tensor memory usage by over 50% compared to float32. - Gradient Accumulation: Micro-batches of 2 to 4 samples accumulated across 8 to 16 steps, yielding an effective batch size of 32 to 64 samples.
- Memory Management: Configured
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:Truealongside explicit VRAM cache clearing between steps.
6. Practical Benchmark: 8-Turn Continuous Dialogue
The model was evaluated on a continuous 8-turn conversational flow in Portuguese. All responses were generated on the RTX 4060 Laptop GPU in 0.37s to 0.98s per turn:
| Turn | User Message (Portuguese) | Intent | Model Behavior | Evaluation |
|---|---|---|---|---|
| 1 | "Oi, tudo bem com você?" | Greeting | Cordial greeting, asked about the user's day. | Natural & Friendly |
| 2 | "O que você mais gosta de fazer?" | Personal query | Stated interest in learning and logic, asked about user hobbies. | Empathetic & Reciprocal |
| 3 | "Hoje meu dia foi bem corrido no trabalho, estou bem cansado." | Venting / Fatigue | Validated exhaustion, suggested winding down. | Grounded & Supportive |
| 4 | "O que você acha de tomar café para espantar o sono?" | Daily habit | Explained caffeine's adenosine receptor blocking and night sleep impact. | Factual & Practical |
| 5 | "Que tipo de música você acha bom para relaxar depois de um dia pesado?" | Relaxation | Suggested quiet genres (Lo-Fi, Bossa Nova, Piano) and asked preferences. | Useful & Direct |
| 6 | "Por que o céu fica avermelhado no final da tarde?" | Science inquiry | Explained atmospheric Rayleigh scattering in accessible language. | Clear & Accurate |
| 7 | "Me dá uma dica rápida para não acordar atrasado amanhã?" | Practical tip | Provided 3 practical habits (alarm distance, night prep, light gap). | Concrete Advice |
| 8 | "Valeu pela conversa, boa noite e até amanhã!" | Farewell | Polite sign-off, wished rest, left the channel open for the next day. | Courteous & Closing |
7. Repository Files
| File | Description |
|---|---|
ncm_sume_generator.pt | Transformer Generator weights (88.61M parameters, ~340 MB) |
ncm_sume_tokenizer.pt | Multiscale Residual VQ-VAE weights (36.43M parameters, ~211 MB) |
bpe_vocab_8192.pickle | BPE tokenizer vocabulary (8,192 tokens) |
bpe_merges_8192.pickle | BPE merges table |
config.json / config.yaml | Architecture configuration and codebook hyperparameters |
generate.py | Standalone PyTorch inference script |
requirements.txt | Runtime dependencies |
README_pt.md | Full documentation in Portuguese |
8. Quickstart & Inference
1. Clone and Install Dependencies
git clone https://huggingface.co/jpnmnb/NCM-Sume-Portuguese-Instruct
cd NCM-Sume-Portuguese-Instruct
pip install -r requirements.txt
pip install git+https://github.com/HazyResearch/ncm.git
2. Run Inference
python generate.py --prompt "Olá, o que você sabe sobre a chuva?"
CLI flags:
--device cudaor--device cpu--precision bfloat16or--precision float32--max_length 128
9. Current Limitations & Roadmap
- Parametric Capacity: With ~88M parameters in the generator, the model is a compact proof-of-concept. Dense historical facts and multi-step math require pairing with retrieval (RAG) to avoid hallucinations.
- Future Work:
- Training with explicit thinking tags (
<think>...</think>). - Tool-calling integration for code execution and live search.
- Exploring NCM concept planning on top of larger pre-trained backbones (1.5B or 3B) via QLoRA.
- Training with explicit thinking tags (
- License: MIT License (consistent with the upstream NCM project).
Resumo em Português
O NCM Sumé é uma prova de conceito baseada no artigo de Stanford "Next-Concept Modeling: Fast, Parallel Coarse-to-Fine Text Generation" (arXiv:2610.14162). O objetivo foi treinar e adaptar a arquitetura para responder comandos e conversar em português usando apenas uma GPU doméstica de 8 GB (NVIDIA RTX 4060 Laptop).
- Gerador: 88,61 milhões de parâmetros.
- Tokenizador VQ-VAE: 36,43 milhões de parâmetros (BPE de 8.192 tokens).
- Datasets: BigCode StarCoder (Python), Everything Instruct Multilingual (Português), Boakpe Historinhas e destilação de 1.500 pares com Qwen 2.5 3B.
- Latência medida: 0,37s a 0,98s por turno em conversação cotidiana.
- Licença: MIT.
Para conferir o texto completo em português com o relato detalhado das decisões técnicas, consulte o arquivo README_pt.md no repositório.