Low-Cost Reinforcement Learning for Vertical-Domain LLMs: A Practical Guide
This article explains how vertical-domain large language models differ from general-purpose models, and why reinforcement learning with verifiable rewards is often a better fit than continued pretraining for narrow tasks. It walks through a production-grade training architecture that decouples generation from training, shows how group relative advantage estimation removes the value network to cut memory usage, and covers reward design, a step-by-step rollout plan, and common pitfalls. You will also find the core code snippets for advantage estimation, the clipped policy loss, and rule-based reward extraction.
1. Vertical-Domain LLMs vs. General-Purpose LLMs: Division of Labor, Not Replacement
A common mistake when comparing vertical-domain and general-purpose LLMs is to place them on the same track and benchmark them on parameter counts and leaderboard scores. A more rigorous view is that general-purpose models pursue breadth and generalization, covering long-tail tasks such as open-domain question answering, writing, coding, and multi-turn dialogue. Vertical-domain models pursue accuracy, stability, controllable cost, and auditable compliance on a specific task distribution.
From an engineering perspective, the differences come down to three areas. First, data distribution: general-purpose training corpora are naturally long-tailed, while vertical-domain data is smaller in scale but higher in annotation quality and clearer in objective. Second, evaluation metrics: general capability relies on composite benchmarks, whereas vertical capability can often be judged by verifiable rules, such as whether the final answer to a math problem is correct or whether all required fields are present in a structured extraction. Third, cost structure: general-purpose models have high inference overhead and latency, while a smaller vertical model can trade fewer parameters for higher throughput on a fixed task.
The right technical path, therefore, is not to replace general-purpose models entirely with small ones, but to use a general-purpose model as the capability foundation and distill and consolidate target-task ability into a small model through domain data and reinforcement learning. When task boundaries are clear and results can be judged automatically, a small model plus reinforcement learning offers the best cost-performance ratio.
2. Why Reinforcement Learning Fits Vertical Tasks Better Than Continued Pretraining
Continued pretraining solves the problem of “the model has never seen this kind of corpus.” Supervised fine-tuning solves the problem of “the model does not output in the required format.” Reinforcement learning solves the problem of “whether the output is correct, and how much better it is.” Vertical tasks often share one key trait: the answer can be verified by a program. Math reasoning, code unit tests, structured information extraction, and rule-based risk-control decisions all fall into the verifiable-reward category.
Reinforcement learning delivers three benefits in these scenarios. First, the reward signal is dense and objective, with no reliance on human preference annotation. Second, the optimization objective aligns directly with business metrics, reducing the gap where offline metrics rise but online performance does not. Third, iteration can be completed with relatively low GPU memory on a small model, giving teams an autonomous and controllable iteration cadence.
3. A General Architecture for Production-Grade Training: Decoupling Training from Inference
A reinforcement learning training system fit for production typically has four layers: a data engine that handles sample loading and batching; an inference engine that generates candidate responses in batches; a training engine that updates parameters; and a distributed coordination layer that handles task orchestration and resource scheduling. The core design principle is decoupling training from inference—the generation stage uses a high-throughput inference backend, the update stage uses a distributed training backend, and the two are connected through a unified orchestration layer.
The traditional approach runs generation and training on the same compute backend. Generation consumes most of the time slice but lacks continuous batching and efficient decoding, so overall utilization is low. After decoupling, the generation stage can achieve several times higher throughput, and end-to-end training time drops significantly. A schematic flow looks like this:
for batch in dataloader: # 1. Load domain dataresponses = generate(batch.prompts) # 2. Generate multiple candidate responses in batchrewards = reward_fn(responses) # 3. Score with rules or a modeladv = group_relative_advantage(rewards) # 4. Group-relative advantagepolicy.update(batch, responses, adv) # 5. Policy updateif step % eval_interval == 0:evaluate_and_save(step) # 6. Evaluate and save a checkpoint
Three engineering concerns also matter: store data in a columnar format for efficient slicing; make the resource ratio between generation and training configurable so neither side sits idle; and decouple checkpoints from evaluation so training can recover reliably after an interruption.
4. Key to GPU Memory Optimization: Replacing the Value Network with Group Relative Advantage
In reinforcement learning, the value network estimates a baseline, but it is comparable in size to the policy network and brings considerable memory and compute overhead. The group relative advantage estimation approach is to sample multiple responses for the same question and use the mean reward of that group as the baseline; each response’s advantage is its reward minus the mean, usually normalized by dividing by the group standard deviation. This removes the value network and, in most configurations, saves more than 30% of GPU memory, making it possible to train a larger model or a longer context on a single GPU.
def group_advantage(rewards, eps=1e-6):r = rewards.reshape(len(rewards), -1)mean = r.mean(dim=1, keepdim=True)std = r.std(dim=1, keepdim=True)return ((r - mean) / (std + eps)).reshape(-1)
The companion streamlined loss keeps only the product of the importance sampling ratio and the advantage, plus clipping to suppress the update magnitude:
def policy_loss(new_lp, old_lp, adv, clip=0.2):ratio = torch.exp(new_lp - old_lp)return -torch.min(ratio * adv,torch.clamp(ratio, 1 - clip, 1 + clip) * adv).mean()
5. Reward Design: The Dividing Line Between Success and Failure
The reward function determines which direction the model evolves. For verifiable tasks, prioritize rule-based rewards: extract the final answer from the model output using agreed markers, compare it with the reference answer, give a positive reward when correct, and give a small negative reward when the format is invalid, so that samples where “the answer is right but cannot be parsed” are avoided.
import redef extract_answer(text):m = re.search(r"####\s*(-?[0-9.,]+)", text)return m.group(1).replace(",", "") if m else Nonedef rule_reward(text, gold):pred = extract_answer(text)if pred is None:return -0.5return 1.0 if pred == gold else 0.0
If a task is hard to express as rules, model-based scoring can be used, but you must watch for the reward being gamed: the model tends to produce long answers that pile up keywords to earn a high score. Mitigations include length penalties, format constraints, periodically calibrating the scorer with human spot checks, and keeping some supervised fine-tuning data as a regularization constraint.
6. Rollout Roadmap and Pitfall Checklist
The recommended order is: first build a high-quality domain dataset and define verifiable metrics; then use supervised fine-tuning to teach the model the output format; next introduce group relative advantage reinforcement learning to improve accuracy; and finally apply quantization and inference acceleration before launch. Five common pitfalls: first, rewards that are too sparse cause training not to converge, which can be densified by adding a format reward; second, too few samples make the group baseline noisy, so the sample count must be balanced against available memory; third, an imbalanced resource ratio between generation and training causes idle time; fourth, too large a learning rate triggers policy collapse, so combine clipping with early stopping; fifth, an evaluation set that does not match the training distribution means offline gains fail to transfer online.
In practice, on a single high-end training GPU, combined with an efficient inference backend and the group relative advantage algorithm, a small model on the order of billions of parameters can gain tens of percentage points in accuracy on verifiable tasks such as math reasoning. This shows that the core barrier in vertical domains lies not in parameter scale but in data quality, reward design, and engineering efficiency. If a team needs elastic compute, a containerized training platform, object storage, and monitoring and alerting, these can be assembled on demand from the general cloud product categories offered by Baidu AI Cloud, letting the team focus its effort on the domain data and reward system that truly determine results.
