# How to Train and Deploy a 64M Open‑Source LLM Inside Your Rails Application

> Learn step‑by‑step how to use the Minimind project to train a 64‑million‑parameter language model in just two hours, integrate it with Ruby on Rails, and

- URL: https://railsdev.io/blog/train-deploy-64m-llm-rails
- Published: 2026-11-21
- Author: Hendra Nicholas (Rails Full-Stack Developer & AI Engineer)

---

A custom LLM Rails approach can mean training a tiny 64M model with MiniMind and serving it inside your app, rather than renting a frontier API. I use this when privacy, cost, and predictable latency matter more than broad world knowledge. It is not a replacement for frontier models, but it is a powerful tool for specific, high-volume, private tasks.

## What is a custom LLM Rails approach?

It is a small model you own, trained on your domain data, and called from Rails like any internal service. I treat it as a product component, not a chatbot bolted onto the side of the app.

The MiniMind project is useful here because it publishes a complete training chain for a very small model. According to the repository at https://github.com/jingyaogong/minimind, the main dense model is about 64M parameters, while the MoE variant is about 198M-A64M. The project is Apache 2.0 licensed and implements core algorithms in native PyTorch rather than hiding them behind high-level abstractions.

That matters for a Rails SaaS because I can inspect the model, change the data, and decide what behavior is worth shipping. I still need product judgment, but I am not locked into a vendor's prompt policy or pricing curve. If you are scoping this kind of work, my [AI software development service](/services/ai-software-development) is the natural place to start.

## When should I train a 64M model instead of calling an API?

Train one when the task is narrow, the data is sensitive, and you can tolerate weaker general reasoning. Call an API when users need broad knowledge, complex planning, or polished long-form answers.

| Option | Best for | Main cost | Main risk |
|---|---|---|---|
| Frontier API | Broad reasoning and fast starts | Per-token spend | Data leaves your app and latency varies |
| MiniMind 64M in Rails | Narrow domain tasks and privacy | GPU training plus hosting | Weaker general knowledge and eval burden |
| Larger open model | Stronger domain accuracy | More infrastructure | Higher memory and operations cost |

I would not replace a general assistant with a 64M model. I would use it for classification, extraction, routing, short summaries, or domain-specific Q&A where the answer space is constrained. The smaller model also gives me a fixed cost profile, which is easier to reason about than token-based billing during a SaaS growth phase.

Consider a legal tech SaaS. You need to extract dates from contracts. A frontier API costs money per page and sends your client's data to a third party. A 64M model trained on your historical contracts can do this locally, instantly, and for free after the initial training cost. The model doesn't need to know what happened in 1999; it just needs to recognize the pattern "Date: [Month] [Day], [Year]".

Another example is internal support triage. You have a Rails app with a ticketing system. You want to automatically tag tickets as "Billing," "Bug," or "Feature Request." A 64M model can learn this classification from your past tickets. It is fast, cheap, and keeps your ticket data private. If the model misclassifies a ticket, the cost is low; a human can fix it. If a frontier API misclassifies it, you have paid for the mistake and potentially leaked data.

The decision is not about intelligence; it is about economics and privacy. If the task is high-volume and low-complexity, a small model wins. If the task is low-volume and high-complexity, an API wins.

## How do I train MiniMind for a Rails SaaS?

Clone MiniMind, install dependencies, download a checkpoint, then run the training scripts that match your stage. The README documents the basic setup and model downloads, so I start there rather than inventing my own pipeline.

```bash
git clone --depth 1 https://github.com/jingyaogong/minimind
cd minimind
pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple
modelscope download --model gongjy/minimind-3 --local_dir ./minimind-3
```

The project covers pretraining, supervised fine-tuning, LoRA, DPO, RLAIF, tool use, and agentic reinforcement learning. For a Rails SaaS, I usually care most about supervised fine-tuning on cleaned domain examples, then LoRA for cheaper iteration. The README also mentions a LoRA merge and export flow through `scripts/convert_model.py`, which is useful when I want one deployable checkpoint instead of a base model plus adapter.

The README reports that the SFT stage can run in about two hours on a single NVIDIA 3090, with a stated GPU rental cost of about three RMB for that period. I treat those numbers as a reference point, not a promise, because data size, sequence length, and hardware availability all change the result. The model is also available from Hugging Face at https://huggingface.co/jingyaogong/minimind-3, which is convenient if my deployment pipeline already expects Transformers-format weights.

### Preparing your data

The most important step is data preparation. MiniMind uses JSONL files for training. You need to create a dataset that looks like the examples you want the model to generate. For a classification task, your data might look like this:

```json
{"instruction": "Classify this ticket: 'I can't log in'", "output": "Bug"}
{"instruction": "Classify this ticket: 'How do I upgrade my plan?'", "output": "Billing"}
```

You need enough examples to cover the variations in your data. If your tickets are messy, your training data must be messy. If your tickets are clean, your training data should be clean. I usually start with a small set of examples for a narrow task. More is better, but only if the quality is high.

### Running the training

Once your data is ready, you run the training script. The MiniMind repository includes scripts for different stages. For a Rails SaaS, I usually start with SFT (Supervised Fine-Tuning). This teaches the model to follow instructions and produce the desired output format.

```bash
python train_sft.py --data_path ./data/sft.jsonl --output_dir ./out/sft
```

This command will train the model on your data. It will take some time, depending on your hardware. The README suggests that a single 3090 can do this in about two hours. If you have a better GPU, it will be faster. If you have a worse GPU, it will be slower.

After training, you have a new model checkpoint. You can use this checkpoint for inference. You can also use LoRA to fine-tune the model further, without retraining the entire model. LoRA is cheaper and faster, and it is a good way to iterate on your model.

## How do I embed the model in Rails?

Treat the model as an internal HTTP service, then wrap calls in a Ruby service object. MiniMind includes an OpenAI-compatible server, so Rails can talk to it with ordinary HTTP instead of a custom protocol.

```ruby
class MiniMindClient
  def initialize(base_url = ENV.fetch("MINIMIND_URL"))
    @base_url = base_url
  end

  def chat(messages)
    uri = URI("#{@base_url}/v1/chat/completions")
    request = Net::HTTP::Post.new(uri)
    request["Content-Type"] = "application/json"
    request.body = {
      model: "minimind-3",
      messages: messages,
      temperature: 0.2
    }.to_json

    response = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(request)
    end

    JSON.parse(response.body)
  end
end
```

I keep this client thin and push business logic into a separate service. That makes it easy to swap the local model for an API during an incident or A/B test. I also store prompts in versioned files or database rows, not scattered through controllers. For broader Rails AI patterns, I often pair this with ideas from my post on [Ruby on Rails AI integration](/blog/ruby-on-rails-ai-integration).

### Deployment

You can deploy the MiniMind server on the same server as your Rails app, or on a separate server. If you deploy it on the same server, you need to make sure that the GPU is available. If you deploy it on a separate server, you need to make sure that the network is fast.

I usually deploy the MiniMind server on a separate server, with a GPU. I use Docker to make the deployment easy. I use a Dockerfile that installs the dependencies and runs the MiniMind server. I use a reverse proxy to route requests from my Rails app to the MiniMind server.

```dockerfile
FROM nvidia/cuda:12.2.0-runtime-ubuntu22.04
RUN apt-get update && apt-get install -y python3-pip
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "serve_openai_api.py"]
```

This Dockerfile installs the dependencies and runs the MiniMind server. You can build this image and run it on a server with a GPU. You can then access the MiniMind server from your Rails app using the `MiniMindClient` class.

### Performance

The performance of the MiniMind server depends on the hardware. On a single 3090, short prompts return quickly enough for most Rails apps. If you need lower latency, you can use a faster GPU or a smaller model.

You can also use quantization to reduce the memory footprint of the model. This can improve performance, but it may reduce accuracy. I usually start with the full-precision model and then try quantization if I need to improve performance.

## What are the trade-offs and risks?

A 64M model is cheap and private, but it is not a drop-in replacement for GPT-class reasoning. The main risk is shipping a feature that looks intelligent in a demo and fails on messy production input.

I mitigate that with narrow prompts, structured outputs, and aggressive evaluation. The MiniMind README mentions compatibility with common inference engines such as llama.cpp, vLLM, and Ollama, which gives me deployment options, but compatibility is not the same as quality. I still need to measure accuracy on my own tasks. My post on [LLM evals for Rails apps](/blog/llm-evals-rails) is the companion piece I would read before launch.

Data quality is the other hard part. A small model learns the shape of your training data quickly, including its mistakes. If my labels are inconsistent, the model will confidently reproduce that inconsistency. I would rather ship a smaller, well-evaluated feature than a broad assistant that hallucinates in production.

### Hallucinations

Small models are more prone to hallucinations than large models. This is because they have less knowledge and less ability to reason. If you ask a 64M model a question that it does not know the answer to, it will make up an answer. This is a problem for tasks that require factual accuracy.

To mitigate this, I use structured outputs. I ask the model to output JSON, and I validate the JSON in my Rails app. If the JSON is invalid, I reject the response and ask the model to try again. I also use a fallback mechanism. If the model fails to produce a valid response, I fall back to a rule-based system or a human review.

### Cost

The cost of training a 64M model is low. The cost of deploying it is also low. However, the cost of maintaining it is not zero. You need to monitor the model, update the data, and retrain the model when the data changes. This is a ongoing cost that you need to budget for.

I usually budget for a few hours of engineering time per month to maintain the model. This is much less than the cost of a frontier API, but it is not free. You need to weigh the cost of maintenance against the cost of the API.

### Privacy

The main advantage of a custom LLM is privacy. Your data never leaves your server. This is a big advantage for sensitive data, such as medical records, financial data, or legal documents. If you are in a regulated industry, privacy is a must. A custom LLM is the only way to get privacy.

However, privacy is not the only advantage. A custom LLM is also faster and cheaper than a frontier API. It is also more reliable, because you are not dependent on a third-party service. If the API goes down, your app still works.

## Frequently asked questions

### Is MiniMind production-ready for a SaaS?

It can be, but only for narrow tasks with clear evaluation. I would not use a 64M model as a general support agent without extensive testing on real user queries.

### Can I run it on CPU?

The README focuses on GPU training, especially a single RTX 3090 for SFT. Inference may run on CPU depending on the engine and quantization, but I would benchmark latency before promising a response time to users.

### Does it support tool calling?

The README says recent MiniMind releases include tool-call and reasoning tags in the chat template, and the OpenAI-compatible server supports tool calls. I would still test my exact tool schema before relying on it.

### How do I evaluate it in Rails?

I log inputs, expected outputs, and model responses, then score them with task-specific checks. For extraction tasks, exact match or schema validation is more useful than a vague quality score.

### Should I use MoE instead of the dense 64M model?

Use MoE when you need more capacity and can afford the larger footprint. The dense 64M model is simpler to deploy and reason about, so I start there unless evaluation shows a clear gap.

## Conclusion

Training a small model is not a shortcut to frontier performance, but it is a practical way to add private, cost-controlled AI features to a Rails SaaS. I would start with one narrow workflow, train on clean examples, and measure it honestly before expanding scope. If you want help designing that roadmap, [book a discovery call](/#contact).

> Verification note: Training time, cost, model sizes, and feature claims above are taken from the MiniMind README and may vary by hardware, dataset, sequence length, and software version. I have not independently benchmarked them in my own environment, and any production deployment should be validated with your own evals.

Primary source: [the official project page](https://github.com/jingyaogong/minimind).
