CoolFace
Modelpublic

MuratcanKoylan/Marketing-Memory-Routing-8B

sourceHugging Faceapache-2.0updated 10mo agoView on Hugging Face
1likes
Model Card

Memory Routing Agent

A specialized 8B model that outperforms its 104B teacher on marketing conversation classification.

![HuggingFace](https://huggingface.co/MuratcanKoylan/Marketing-Memory-Routing-8B) ![GitHub](https://github.com/muratcankoylan/memory-routing-agent) ![License](LICENSE)


The Experiment

This project demonstrates prompt distillation: training a small, specialized model to outperform the large model that generated its training data.

The Challenge

Marketing AI assistants need to remember the right information from conversations. Not everything is worth storing - you need to distinguish between:

  • โ€”Valuable: "Our brand voice is professional but approachable" โ†’ Store in long-term memory
  • โ€”Transactional: "What time is the meeting tomorrow?" โ†’ Don't store

This is a 13-category classification problem with nuanced distinctions between company-level and user-level information, different persistence horizons, and the critical ability to say "none" for irrelevant content.

The Approach

  1. 1.Generate synthetic data using Cohere Command-R-Plus (104B) as the teacher
  2. 2.Fine-tune Llama-3.1-8B with LoRA using Tinker's training platform
  3. 3.Apply reinforcement learning with a custom reward function
  4. 4.Benchmark against the teacher on challenging, held-out scenarios

The Result

ModelParametersAvg F1Exact Match
Ours8B0.6860%
Cohere Command-R-Plus104B0.6126%

Our 8B model achieves 11.1% higher F1 and 2.3x better exact match accuracy than the 104B teacher, while being 13x smaller.

The student surpassed the teacher through:

  • โ€”Focused training: The model only learns this one task, not general capabilities
  • โ€”RL refinement: The reward function optimizes for exact category matching, not just plausible outputs
  • โ€”Clean data: Synthetic data with consistent labeling, no noise from human annotation disagreements

Training Visualizations

Phase 1: Supervised Fine-Tuning

[image]

100 training steps reduced loss from 5.47 to 0.26 (95% reduction). The model learned the basic classification task in the first epoch.

Phase 2: Reinforcement Learning

[image]

30 RL iterations improved mean reward from 0.73 to 0.93. The reward function combines F1 score, temporal alignment, scope correctness, and storage efficiency.

Model Comparison

[image]

Our model excels at exact matching (60% vs 26%) because RL optimizes for getting all categories right, not just some.

Performance by Difficulty

[image]

The 8B model dominates on easy cases (+79% F1) and matches on medium cases. The 104B model still wins on hard multi-label scenarios.


Key Results

MetricOur Model (8B)Cohere (104B)
Avg F10.680.61
Exact Match60%26%
Any Match72%82%
Model Size8B104B
Improvement+11.1% F1baseline

Reward Components (Final RL Iteration)

ComponentScoreDescription
R_F10.90F1 score vs gold labels
R_temp0.95Temporal alignment
R_parity1.00Company/user scope
R_eff1.00Storage efficiency

What It Does

The Memory Routing Agent classifies marketing conversations into 13 memory categories:

Company Categories (Long-term business context)

CategoryDescriptionPersistence
company.brand_coreVoice, values, positioningLong (>1y)
company.strategic_signaturesDecision frameworksLong (>1y)
company.knowledge_artifactsDocs, style guidesLong (>1y)
company.business_prioritiesQuarterly goalsShort (<3m)
company.tools_configIntegrations, APIsMedium (~6m)
company.performance_contextCampaign metricsRolling (~6m)

User Categories (Personal preferences)

CategoryDescriptionPersistence
user.communication_styleTone, format preferencesLong (>1y)
user.strategic_approachPersonal prioritiesLong (>1y)
user.role_contextTitle, scopeMedium (~1y)
user.workflow_patternsReview cadenceMedium (~1y)
user.session_historyImmediate contextShort (<2w)
user.interaction_preferencesCoaching styleEvolving

Special

CategoryDescription
noneTransactional or irrelevant content

Training Pipeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    TRAINING PIPELINE                            โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚                                                                 โ”‚
โ”‚  1. SYNTHETIC DATA GENERATION                                   โ”‚
โ”‚     โ”œโ”€โ”€ Cohere Command-R-Plus (104B) as teacher                โ”‚
โ”‚     โ”œโ”€โ”€ 2,001 marketing conversations                          โ”‚
โ”‚     โ””โ”€โ”€ 13 category labels + persistence horizons              โ”‚
โ”‚                                                                 โ”‚
โ”‚  2. SUPERVISED FINE-TUNING (SFT)                               โ”‚
โ”‚     โ”œโ”€โ”€ Base: meta-llama/Llama-3.1-8B                          โ”‚
โ”‚     โ”œโ”€โ”€ LoRA rank 32                                           โ”‚
โ”‚     โ”œโ”€โ”€ 100 steps, batch size 128                              โ”‚
โ”‚     โ””โ”€โ”€ Cross-entropy loss                                     โ”‚
โ”‚                                                                 โ”‚
โ”‚  3. REINFORCEMENT LEARNING (RL)                                โ”‚
โ”‚     โ”œโ”€โ”€ 30 iterations, 64 groups ร— 32 samples                  โ”‚
โ”‚     โ”œโ”€โ”€ Importance sampling policy gradient                    โ”‚
โ”‚     โ””โ”€โ”€ Composite reward: F1 + temporal + parity + efficiency  โ”‚
โ”‚                                                                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Reward Function

R_total = 0.6 ร— R_F1 + 0.2 ร— R_temp + 0.1 ร— R_parity + 0.1 ร— R_eff
ComponentWeightDescription
R_F160%F1 score vs gold labels
R_temp20%Persistence horizon alignment
R_parity10%Company/user scope correctness
R_eff10%Storage efficiency (โ‰ค3 categories)

Quick Start

Installation

bash
# Clone the repository
git clone https://github.com/muratcankoylan/memory-routing-agent.git
cd memory-routing-agent

# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

Environment Setup

bash
# Create .env file with your API keys
echo "TINKER_API_KEY=your_tinker_key" >> .env
echo "COHERE_API_KEY=your_cohere_key" >> .env
echo "HF_TOKEN=your_huggingface_token" >> .env

Run Inference

python
import tinker
from tinker import types
from tinker_cookbook import renderers
from tinker_cookbook.tokenizer_utils import get_tokenizer

# Load model from Tinker checkpoint
service_client = tinker.ServiceClient()
checkpoint = "tinker://4f4bae1f-5a95-5f53-a55a-a14f2872825c:train:0/sampler_weights/rl_iter_012"
sampling_client = service_client.create_sampling_client(model_path=checkpoint)

# Setup tokenizer and renderer
tokenizer = get_tokenizer("meta-llama/Llama-3.1-8B")
renderer = renderers.get_renderer(name="llama3", tokenizer=tokenizer)

# Classify a conversation
conversation = """
USER: Our brand voice is professional but approachable. Think Harvard Business Review meets Slack.
ASSISTANT: So authoritative content with a conversational tone?
USER: Exactly. We never use jargon without explaining it first.
"""

messages = [
    {"role": "system", "content": "You route marketing conversations into structured memory categories..."},
    {"role": "user", "content": f"Analyze this conversation:\n\n{conversation}"}
]

prompt = renderer.build_generation_prompt(messages)
params = types.SamplingParams(max_tokens=100, temperature=0.1, stop=renderer.get_stop_sequences())
result = sampling_client.sample(prompt=prompt, sampling_params=params, num_samples=1).result()

response, _ = renderer.parse_response(result.sequences[0].tokens)
print(f"Categories: {response['content']}")
# Output: company.brand_core

Project Structure

memory-routing-agent/
โ”œโ”€โ”€ assets/                   # Training visualizations
โ”‚   โ”œโ”€โ”€ sft_loss.png
โ”‚   โ”œโ”€โ”€ rl_reward.png
โ”‚   โ”œโ”€โ”€ rl_components.png
โ”‚   โ”œโ”€โ”€ model_comparison.png
โ”‚   โ””โ”€โ”€ difficulty_comparison.png
โ”œโ”€โ”€ synthetic_data/           # Data generation pipeline
โ”‚   โ”œโ”€โ”€ pipeline.py           # Cohere-based conversation generator
โ”‚   โ”œโ”€โ”€ run_diverse_generation.py
โ”‚   โ””โ”€โ”€ merged_training_dataset_2001.jsonl
โ”œโ”€โ”€ training/                 # Training scripts
โ”‚   โ”œโ”€โ”€ train_v2.py           # Main training script (SFT + RL)
โ”‚   โ”œโ”€โ”€ preprocess.py         # Data preprocessing
โ”‚   โ”œโ”€โ”€ rl_env.py             # RL environment and reward function
โ”‚   โ”œโ”€โ”€ final_benchmark.py    # Benchmark evaluation
โ”‚   โ”œโ”€โ”€ logs/                 # Training logs (JSONL)
โ”‚   โ””โ”€โ”€ benchmarks/           # Benchmark results
โ”œโ”€โ”€ huggingface/              # HuggingFace upload scripts
โ”œโ”€โ”€ docs/                     # Documentation
โ”‚   โ”œโ”€โ”€ PRD.md                # Product requirements
โ”‚   โ””โ”€โ”€ tinker_docs.md        # Tinker reference
โ”œโ”€โ”€ MODEL_CARD.md             # Model card
โ””โ”€โ”€ README.md                 # This file

Benchmark

The Marketing Routing Benchmark contains 50 challenging scenarios across 7 domains:

DomainScenariosDescription
Brand & Positioning8Brand voice, values, identity
Strategic Decisions8Decision frameworks, heuristics
Performance & Metrics8Campaign metrics, learnings
Tools & Integrations6Tech stack, APIs
User Preferences10Communication style, workflow
Business Priorities6Goals, focus areas
Knowledge Artifacts4Docs, playbooks, templates

Run Benchmark

bash
python training/final_benchmark.py

Training Your Own Model

1. Generate Synthetic Data

bash
cd synthetic_data
python run_diverse_generation.py --num_items 1000

2. Preprocess Data

bash
python training/prepare_data.py

3. Run Training

bash
python training/train_v2.py

4. Evaluate

bash
python training/final_benchmark.py

Limitations

  • โ€”Multi-label: Under-predicts when multiple categories apply
  • โ€”Overlap: Struggles with company/user category overlap on edge cases
  • โ€”Domain: Marketing-specific; not tested on other domains

Links


Citation

bibtex
@misc{memory-routing-agent-2025,
  title={Memory Routing Agent: Prompt Distillation for Marketing AI},
  author={Muratcan Koylan},
  year={2025},
  howpublished={\url{https://github.com/muratcankoylan/memory-routing-agent}},
}

License

Apache 2.0


Acknowledgments

  • โ€”Thinking Machines for the Tinker training platform
  • โ€”Cohere for Command-R-Plus teacher model
  • โ€”Meta for Llama 3.1 base model
  • โ€”Anthropic for Claude, which assisted in developing this project