ShVaSa Blog
Tech & AI • 5 min read

Show Your Work in Swahili: Reinforcement Learning for Native-Language Mathematical Reasoning

Published on 2026-11-14 by Sharath Japa, ShVaSa Lab Lead
aitechdeep-learningmultimodal
Discuss on r/shvasa

Executive Summary

The deployment of Large Language Models (LLMs) in low-resource linguistic contexts, specifically Swahili, exposes critical gaps in mathematical reasoning capabilities due to data scarcity and cultural-linguistic misalignment. The Fikiria framework addresses this by introducing a two-stage training pipeline: Supervised Fine-Tuning (SFT) followed by Group Relative Policy Optimization (GRPO). Unlike standard Reinforcement Learning from Human Feedback (RLHF) which relies on separate reward models, Fikiria employs a self-verified reward mechanism. The core innovation lies in a composite reward function that multiplies a strict format gate by a weighted sum of answer accuracy and a "show your work" metric. This architecture forces the model to generate intermediate reasoning steps in Swahili before committing to a final numerical answer, thereby reducing hallucination rates and improving logical consistency. The system prioritizes native-language fluency, ensuring that the reasoning trace is not merely a translation of English logic but a culturally coherent mathematical exposition.

Implementation

The technical core of Fikiria is the GRPO algorithm, which optimizes the policy $\pi_\theta$ by comparing a group of $G$ sampled responses against their group mean, eliminating the need for a critic model. This significantly reduces VRAM consumption during training. The reward function $R$ is defined as:

$$R = R_{\text{format}} \times (\alpha R_{\text{accuracy}} + \beta R_{\text{reasoning}})$$

Where $R_{\text{format}}$ is a binary gate (1 if the output contains a valid Swahili reasoning block and final answer tag, 0 otherwise). $R_{\text{accuracy}}$ is derived from exact match or symbolic equivalence checks. $R_{\text{reasoning}}$ evaluates the semantic coherence of the intermediate steps using a lightweight Swahili-specific semantic encoder.

Memory and Scheduling Bottlenecks

The primary bottleneck in this pipeline is the memory bandwidth required to handle the large batch sizes necessary for stable GRPO updates. Since GRPO samples $G$ responses per prompt, the activation memory scales linearly with $G$. To mitigate this, we employ:

  1. PagedAttention: To manage KV-cache fragmentation during the generation phase.
  2. Gradient Checkpointing: To trade compute for memory during the backpropagation phase.
  3. Mixed Precision Training: Using BF16 for activations and FP32 for loss scaling to prevent underflow in the reward calculation.

The following Python snippet illustrates the core reward computation logic, specifically the format gate and accuracy check:

PYTHON
import re
import torch

def compute_fikiria_reward(completion: str, ground_truth: str) -> dict:
    """
    Computes the composite reward for Fikiria model.
    """
    # 1. Format Gate: Check for Swahili reasoning block and final answer tag
    # Expected format: <reasoning> ... </reasoning> <answer> ... </answer>
    pattern = r"<reasoning>(.*?)</reasoning>\s*<answer>(.*?)</answer>"
    match = re.search(pattern, completion, re.DOTALL)
    
    if not match:
        return {"reward": 0.0, "format_score": 0.0, "accuracy_score": 0.0}
    
    reasoning_text = match.group(1).strip()
    final_answer = match.group(2).strip()
    
    format_score = 1.0
    
    # 2. Accuracy Score: Symbolic equivalence check
    # In production, use sympy or a custom parser for Swahili number words
    try:
        # Simplified for demonstration: direct string match or numeric eval
        is_correct = (final_answer == ground_truth) or (float(final_answer) == float(ground_truth))
        accuracy_score = 1.0 if is_correct else 0.0
    except ValueError:
        accuracy_score = 0.0
        
    # 3. Reasoning Score: Placeholder for Swahili semantic coherence model
    # This would involve embedding the reasoning_text and comparing against 
    # a gold-standard reasoning embedding vector.
    reasoning_score = 0.5  # Dummy value for illustration
    
    alpha = 0.7  # Weight for accuracy
    beta = 0.3   # Weight for reasoning quality
    
    # Composite Reward
    total_reward = format_score * (alpha * accuracy_score + beta * reasoning_score)
    
    return {
        "reward": total_reward,
        "format_score": format_score,
        "accuracy_score": accuracy_score,
        "reasoning_score": reasoning_score
    }

ShVaSa Intuition

The intuition behind Fikiria is that mathematical reasoning in low-resource languages suffers from "translation decay." When models trained primarily on English data attempt to solve math problems in Swahili, they often skip the logical derivation and jump to a predicted token based on superficial pattern matching. By enforcing a "show your work" constraint via the format gate, we compel the model to allocate attention to the logical steps. The Swahili language, with its agglutinative structure and rich noun class system, requires specific syntactic markers for logical connectors (e.g., kwa hiyo for "therefore"). The reward function implicitly encourages the model to learn these connectors as part of the reasoning chain, rather than treating them as mere linguistic filler. This creates a deterministic path from problem statement to solution, grounded in the native linguistic logic of the user.

graph TD
    A[Swahili Math Problem] --> B(SFT Stage: Supervised Fine-Tuning)
    B --> C[Generate Initial Reasoning & Answer]
    C --> D{Format Gate Check}
    D -- Fail --> E[Penalize: Reward = 0]
    D -- Pass --> F[Parse: Reasoning & Answer Blocks]
    F --> G[Calculate Accuracy Score]
    F --> H[Calculate Reasoning Coherence Score]
    G --> I[Weighted Sum: α*Acc + β*Reasoning]
    H --> I
    I --> J[GRPO Update: Group Relative Policy Optimization]
    J --> K[Updated Policy π_θ]
    K --> C
    E --> J

Protocol Guarantees and Evaluation

The system guarantees that any output with a non-zero reward strictly adheres to the <reasoning> and <answer> schema. This structural rigidity is crucial for downstream parsing in educational applications. Evaluation on the Fikiria benchmark demonstrates a 15% improvement in exact match accuracy compared to standard SFT models, with a significant reduction in "nonsense" outputs where the model generates Swahili text that is syntactically correct but mathematically incoherent. The use of GRPO ensures that the training process remains stable even with the sparse reward signals typical of mathematical verification tasks. Future work will focus on expanding the Swahili reasoning corpus to include domain-specific terminology from engineering and finance, further refining the $R_{\text{reasoning}}$ component.


Grounding & Source Attribution

Author Avatar

Sharath Japa, ShVaSa Lab Lead

Systems & AI Infrastructure Researcher, DGX Station homelab lead. Engineering RL environments, edge silicon inference, and local reasoning model distillation. Verified Profiles: Google Scholar • Google Patents • LinkedIn • GitHub (@sharathjapa) • Medium • r/shvasa.


Canonical Source: https://shvasa.us/posts/show-your-work-in-swahili-reinforcement-learning-for-native-language-mathematical-reasoning

Advertisement

Related Research & Architectural Blueprints