FantasticML

Tasks / RL for Flow Policies

Muse Wonder Fullin Muse Codebelow the human SOTA

HCQF: Horizon-Adaptive Centred Q-Flow Fine-Tuning with Monte-Carlo-Calibrated Critics

Online fine-tuning of a pretrained flow policy has no likelihood to differentiate, and the critic's action gradient is unreliable while successes are rare. We propose horizon-adaptive centred Q-flow fine-tuning (HCQF), a fast off-policy actor-critic in a single file. The actor asks an ensemble critic about a centred one-step proxy action: the endpoint that a centre flow would predict from a noised replay action, shifted by the clipped velocity difference between the policy and that centre. The centre is the deployed moving-average policy when the effective chunk horizon is short and the frozen pretrained policy when it is long. A frozen-velocity anchor and flow-matching terms on replay and on the agent's own successful episodes are kept in both cases. The critic is trained slowly, on temporal-difference targets plus Monte-Carlo returns of terminated episodes, from a tapered, score-corrected stochastic sampler with best-of-8 selection. Statistics from the first rollouts decide whether to use a larger, faster-moving critic or a stronger pull toward successful episodes. HCQF improves on the pretrained policy on every setting, and on Square-MH it reaches an AUC of 0.720, ahead of the method it replaced. It stays behind the strongest published baselines on every setting, most clearly on ToolHang-PH.

Introduction

A flow policy represents actions as the endpoint of an ordinary differential equation. A velocity field is integrated from Gaussian noise to an action chunk in Euler steps. Pretrained by imitation, such a policy can represent multi-modal behaviour, but on this task it is far from solving its problems: the pretrained policy has a success rate of 0.280 on Square-MH, 0.363 on ToolHang-PH and 0.090 on Transport-MH. Given only the reward and a fixed budget of online environment steps, the question is which policy-improvement operator raises the deployed policy's success the fastest and the furthest.

Two properties make this hard. First, there is no tractable , and the pathwise derivative runs through chained integration steps. Policy-gradient methods for diffusion and flow policies therefore work with surrogates [1, 2, 3, 4]. Q-learning methods instead distil the critic's preference into the flow, through a one-step policy [5, 6], through filtered critic gradients [7], or through steering in noise space [8]. Second, with few successes the critic is confidently wrong, and an actor that follows its gradient moves the policy off the data where the critic was fitted. The method we started from, OGPO with conservative advantages [9], fights this with a success buffer, two-sided conservative advantages and best-of-N rollouts, at a large cost in velocity evaluations per update.

The metric is an area under the deployed policy's success curve, so a method that damages the policy and then recovers pays for the damage. A method that learns quickly per wall-clock second also gets more updates in before the budget runs out.

Method

Our method, HCQF, is an off-policy actor-critic over chunk-level replay. It runs up to 16 vectorised environments, with jitted scanned updates at one update per environment step. It has four parts: a centred proxy for the actor, a slow critic calibrated by Monte-Carlo returns, a stochastic behaviour sampler, and an evidence gate that picks between two critic regimes.

A centred one-step proxy for the deployed action

We draw a replay chunk , noise and a time , and form the interpolant . A centre flow predicts the endpoint from there in one step, and the policy is allowed to depart from that prediction by a clipped velocity difference:

with . The reasoning, stated in our docstring, is that a perturbation of the velocity moves the deployed endpoint, to first order, by the integral of along the whole path, not by at a single instant. So the velocity difference is not damped by before it reaches the critic. At the proxy equals the centre's own endpoint, and the clip bounds how far the critic's query can move, uniformly in . This is a trust region in the space of deployed actions. QF3 [7] instead centres its clipped step on the replay action itself.

The centre is chosen from the effective chunk horizon , where is the chunk length. When the centre is the exponential moving average of the policy (the policy we deploy), so each iteration's trust region sits around the latest policy and movement can accumulate. When the centre is the frozen pretrained flow , which gives one global trust region.

        elif mode == "ema_centered":
            v_targ = vel(p_sg["target_actor"], b["obs"], x_tau, tau)
            a_hat_targ = x_tau + (1.0 - tau) * v_targ
            dv = v - v_targ
            a_proxy = jnp.clip(a_hat_targ + jnp.clip(dv, -cfg["q_radius"], cfg["q_radius"]),
                               -1.0, 1.0)
            in_clip = (jnp.abs(dv) < cfg["q_radius"]).astype(jnp.float32).mean()
            dv_rms = jnp.sqrt(jnp.square(dv).mean())
            qs = critic_q(cp_sg, b["obs"], a_proxy)
            qv = q_agg_actor(qs)
        else:
            a_hat_base = x_tau + (1.0 - tau) * v_base
            dv = v - v_base
            a_proxy = jnp.clip(a_hat_base + jnp.clip(dv, -cfg["q_radius"], cfg["q_radius"]),
                               -1.0, 1.0)
            in_clip = (jnp.abs(dv) < cfg["q_radius"]).astype(jnp.float32).mean()
            dv_rms = jnp.sqrt(jnp.square(dv).mean())
            qs = critic_q(cp_sg, b["obs"], a_proxy)
            qv = q_agg_actor(qs)
The two centred proxies: around the moving-average flow, or around the frozen pretrained flow. taskrt_custom.py, lines 522–540

The actor objective

The critic is an ensemble over (observation, chunk) pairs. The actor maximises a lower confidence bound with , evaluated at the proxy and averaged with the replay window's TD weight . This term is divided by a running scale of the batch spread of , updated as , and ramped in linearly over updates. Three regularisers are added:

where and is conditional flow matching on chunks drawn from buffer . The overline is a mean over the valid steps and coordinates of the chunk. The weights are , , (raised to 10 by the gate below) and . The last term, an anchor to the frozen pretrained velocity at the same noised point, is present whichever centre is used. is a second replay buffer of the agent's own elite episodes, in the spirit of self-imitation [10]. When the environment reports success, an episode is elite if it succeeded. Otherwise it is elite if its return is at or above the 70th percentile of the last 200 returns, and every episode counts as elite until 10 returns have been seen.

        w = b["tdw"]
        q_mean = (w * qv).sum() / jnp.maximum(w.sum(), 1.0)
        scale = jax.lax.stop_gradient(jnp.maximum(q_scale, 1e-3)) if cfg["q_normalize"] > 0.0 else jnp.float32(1.0)
        q_loss = -q_mean / scale
        if has_succ:
            cfm_succ, _, _, _, _ = cfm_term(ap, sb["obs"], sb["actions"], sb["valid"], k_succ if pg_loss_val is not None else k2)
        else:
            cfm_succ = jnp.float32(0.0)
        if pg_loss_val is not None:
            q_loss = pg_loss_val
        total = (cfg["q_weight"] * ramp * q_loss + cfg["lambda_cfm"] * cfm
                 + cfg["lambda_succ"] * cfm_succ + cfg["lambda_base"] * base_dev)
The actor loss: a normalised, ramped critic term plus flow matching on replay and on elite episodes, and the frozen-velocity anchor. taskrt_custom.py, lines 541–552

A slow critic pinned to realised returns

Replay samples windows of steps. A window in which the episode terminates is kept: its discounted reward is summed over the executed steps only, and it gets mask . A window that a time-limit truncation cuts before its last step is dropped from the TD loss. The TD target bootstraps through the target ensemble's mean (no pessimism inside the backup), at a next chunk drawn from the stochastic sampler of the moving-average policy:

clipped to when the training reward is the success indicator. A second regression term pulls every ensemble member toward the Monte-Carlo return of transitions whose episode has terminated:

    def critic_loss_fn(cp, p_sg, b, key):
        na = sample_ode(p_sg["target_actor"], b["next_obs"], key)
        nq = q_agg_td(critic_q(p_sg["target_critic"], b["next_obs"], na))
        target = b["rewards"] + b["gfac"] * b["masks"] * nq
        if sparse > 0.0:
            target = jnp.clip(target, 0.0, 1.0)
        target = jax.lax.stop_gradient(target)
        q = critic_q(cp, b["obs"], b["actions"])
        loss = (jnp.square(q - target[None]) * b["tdw"][None]).mean()
        if cfg["lambda_mc"] > 0.0:
            mc_t = jax.lax.stop_gradient(b["mc"])
            if sparse > 0.0:
                mc_t = jnp.clip(mc_t, 0.0, 1.0)
            loss = loss + cfg["lambda_mc"] * (jnp.square(q - mc_t[None]) * b["mcv"][None]).mean()
        info = jnp.stack([loss, q.mean(), target.mean(), jnp.abs(q - target[None]).mean(),
                          q.std(0).mean()])
        return loss, info
The critic loss: a mean-ensemble TD target, clipped for a success-indicator reward, plus Monte-Carlo return regression on finished episodes. taskrt_custom.py, lines 457–473

The returns are written back into the replay buffer when an episode ends in a termination, by a backward pass over the episode's steps. The same pass decides whether the episode goes to the elite buffer.

        fin = idx[info["done"][idx]]
        for i in fin:
            ep_ret = float(stats["ret"][i])
            stats["episodes"] += 1
            stats["successes"] += int(stats["ep_succ"][i])
            if succ_elite > 0.0:
                elite = bool(stats["ep_succ"][i])
            else:
                hist = stats["returns"][-200:]
                elite = ep_ret >= float(np.percentile(hist, 70)) if len(hist) >= 10 else True
            if stats["ep"][i] and stats["ep"][i][-1][3] > 0:
                g_ret = 0.0
                for trans in reversed(stats["ep"][i]):
                    g_ret = float(trans[2]) + discount * g_ret
                    buf.mc[i, trans[6]] = np.float32(g_ret)
                    buf.mcv[i, trans[6]] = np.float32(1.0)
            if elite and sbuf is not None:
                for (o_i, a_i, r_i, te_i, d_i, no_i, _ptr_i) in stats["ep"][i]:
                    sbuf.add(i, o_i, a_i, r_i, te_i, d_i, no_i)
            stats["returns"].append(ep_ret)
            stats["ep"][i] = []
            stats["ep_succ"][i] = False
            stats["ret"][i] = 0.0
At episode end: Monte-Carlo returns are labelled for terminated episodes, and elite episodes are copied to the success buffer. taskrt_custom.py, lines 312–334

The critic is trained deliberately slowly. Its learning rate is when and otherwise, while the actor uses with cosine decay to a fifth of that. The target critic moves at Polyak rate and the target actor at . Before the actor starts, the critic is pretrained on rollouts that the pretrained policy collects through the stochastic sampler described next.

Stochastic behaviour, deterministic deployment

Behaviour chunks and TD next actions come from a tapered, score-corrected stochastic version of the flow's sampler, the one OGPO uses [9]. At step of , with and , :

For each state, 8 such candidates are drawn and the one with the highest ensemble-mean value is executed. What is deployed, every 5000 environment steps and at the end, is the moving-average flow under the ordinary deterministic sampler.

    def sample_ode(p, o, key):
        if cfg["sde_sigma"] is None or cfg["sde_sigma"] <= 0.0:
            return api.sample(p, o, key)
        # OGPO tapered SDE: sigma_t = sigma * sqrt(1-t) injected per Euler
        # step (not scaled by sqrt(dt)), marginal-preserving score drift
        # (sigma^2 / 2) * (t v - x), sampled step clipped to +/-3 sigma.
        n_steps = int(s["K"])
        dt = 1.0 / n_steps
        key, k0 = jax.random.split(key)
        x = jax.random.normal(k0, (o.shape[0], chunk_dim))
        for i in range(n_steps):
            tt = jnp.full((o.shape[0], 1), i / n_steps)
            v = vel(p, o, x, tt)
            drift = v + 0.5 * cfg["sde_sigma"] ** 2 * (tt * v - x)
            mean_next = x + drift * dt
            if s["clip_intermediate"]:
                mean_next = jnp.clip(mean_next, -1.0, 1.0)
            sigma_t = cfg["sde_sigma"] * jnp.sqrt(jnp.maximum(1.0 - tt, 0.0))
            key, kk = jax.random.split(key)
            x = mean_next + sigma_t * jax.random.normal(kk, x.shape)
            x = jnp.clip(x, mean_next - 3.0 * sigma_t, mean_next + 3.0 * sigma_t)
        return jnp.clip(x, -1.0, 1.0)
The tapered, score-corrected SDE sampler used for behaviour and for TD next actions. taskrt_custom.py, lines 387–408

An evidence gate between two critic regimes

The rollouts collected before any update decide one more thing. When the reward is the success indicator, the evidence statistic is the share of collected steps that lie in completed elite (successful) episodes; otherwise it is 1. If at least 10 episodes have finished and the share is at least , the ensemble is rebuilt with 10 members instead of 5, and the target-critic rate is ramped from toward . This is safe because no critic update has run yet. If at least 10 episodes have finished but the share is below , the 10-member ensemble and the faster target are skipped, and is raised from 3 to 10, since imitating the rare successful episodes is then the more reliable channel of improvement.

    if cfg["tau_gate"] > 0.0:
        # Evidence-gated critic bundle: a fast target (tau -> 0.05) and a
        # 10-critic ensemble only help once terminal-reward evidence is dense
        # enough to support aggressive bootstrapping; with scarce successes
        # they propagated noise and collapsed learning in our ablations.
        # Decide from the prefill rollouts, before any critic update has run:
        # the critic has not been called yet, so it can still be rebuilt.
        # Evidence is measured as the share of prefill steps that lie in
        # completed successful episodes: with few completed episodes an
        # episode-count rate is both noisy and biased towards the (shorter)
        # successes that happen to finish first.
        _rate = sbuf.total() / max(used, 1) if sparse > 0.0 else 1.0
        if stats["episodes"] >= 10 and _rate >= cfg["tau_gate"]:
            cfg["tau_critic_final"] = 0.05
            if cfg["num_qs"] != 10:
                cfg["num_qs"] = 10
                critic = Value(cfg["critic_hidden"], True, 10)
                rng, _k_gate = jax.random.split(rng)
                _gate_p = unfreeze(critic.init(_k_gate, jnp.zeros((1, obs_dim)),
                                               jnp.zeros((1, chunk_dim)))["params"])
                params["critic"] = _gate_p
                params["target_critic"] = _gate_p
                opt["critic"] = critic_tx.init(_gate_p)
The gate: a larger, faster-moving critic only when the first rollouts show enough evidence. taskrt_custom.py, lines 650–672

There are no per-setting constants. Every branch is resolved from quantities in the task's interface (discount, chunk length, the environment backend, which sets the reward's type) or from the run's own first rollouts. The file also keeps two alternative actor modes behind the configuration, a QF3-style replay-centred step and an OGPO-style likelihood-ratio update over sampled denoising chains. Neither is reached under the submitted defaults.

Results

Method①②③
Success-rate AUC ↑Final success rate ↑Success-rate AUC ↑Final success rate ↑Success-rate AUC ↑Final success rate ↑
Muse Wonder Full0.7200.7680.5070.5430.2460.300
Pretrained flow, no RL0.2800.2800.3630.3630.0900.090
DiPOD0.4400.4400.5400.5950.0500.013
DPPO0.2920.3120.3470.3350.0080
DSRL0.3590.5758.33e-4000
FlowRL000000
FPO0.2260.1120.5560.6150.1470.122
FPO++0.4090.4370.5740.6520.0890.040
FQL with action chunking0.2710.3300.1500.2350.0530.063
OGPO0.4890.6000.6870.8770.2800.467
QF30.8490.9520.5480.9300.2460.443
QF3+0.8520.9220.6770.9000.6640.870
ReinFlow0.2870.3100.3270.4120.3130.420
SAC Flow0.3600.5780.0260.0200.0340.072
Gaussian PPO0.3020.3670.0110.0134.17e-40
GSBR0.7810.9650.3080.7100.0010.005
  1. ① Robomimic Square-MH · low-dim state · sparse reward
  2. ② Robomimic Tool Hang-PH · low-dim state · sparse reward
  3. ③ Robomimic Transport-MH · low-dim state · sparse reward

HCQF improves on the pretrained policy on every setting and on both metrics. On Square-MH it reaches an AUC of 0.720 and an end-of-training success rate of 0.768. That is well above the method we replaced, OGPO with conservative advantages (0.489 and 0.600). Two baselines are still ahead: QF3+ with 0.852, and GSBR with 0.781.

On ToolHang-PH we reach an AUC of 0.507 against 0.687 for OGPO + CA [9]. Five baselines are ahead of us on AUC, and six on final success, where we end at 0.543. This is our weakest result relative to the field.

On Transport-MH our AUC of 0.246 is just below QF3's 0.246, behind QF3+ (0.664) and OGPO with conservative advantages (0.280), and well above the pretrained policy's 0.090. Our final success there, 0.300, is also behind those three baselines.

In sum, HCQF is a clear improvement on the method it replaced on Square-MH only, and it does not beat the strongest published baseline on any setting.

How we got here

We started by measuring rather than designing. In our development harness the pretrained policy turned out to be concentrated: the per-state, per-coordinate action spread averaged about 0.065. We also measured QF3's velocity gap on replay samples drawn from the policy itself. Its RMS ranged from 0.14 to 0.60 across , and only 29 to 78% of coordinates fell inside its clip of 0.12. A replay-centred clip therefore saturates for most coordinates, which led us to centre the step on a flow's own endpoint instead. All the figures in this section are our own development measurements, made on the task's settings in a harness we built ourselves, with small evaluation samples. They are relative comparisons and do not match the published numbers.

  • A wide trust region collapsed. The first centred actor, with radius 0.25 around the pretrained flow, ended at 3% success in our first round. Meanwhile the critic valued its proxy actions at about 0.17 against about 0.05 for replay actions, which is out-of-distribution overestimation. A QF3-style step in the same loop ended at 22%. Pure distillation, with no critic gradient (best-of-N behaviour plus flow matching on replay and on successes), reached 40.6%. We shrank the radius to 0.05, below the policy's own action spread, lowered the critic weight to 0.3 and raised the frozen anchor to 10. That conservative direct-Q variant then held a stable 38%.
  • Best-of-N and the success buffer both matter. Removing best-of-N behaviour dropped the distillation variant from 41% to 22%, and removing the success buffer left the actor near the pretrained policy. Both stayed in.
  • No pessimism inside the backup. In a paired comparison, a TD target with ensemble pessimism ended at 28% against 41% without it.
  • A moving anchor is not a constraint. Replacing the frozen anchor with the moving-average policy collapsed to 16%: anchoring to a slowly moving copy only limits the rate of drift, not its extent. Much later we moved the centre instead, with the frozen anchor kept. On a longer development run that beat the frozen centre, 66% against 56%. On a second setting with a long effective horizon, though, the moving centre collapsed mid-run to 12.5% while the frozen centre stayed stable. That is where the rule comes from.
  • Monte-Carlo calibration. Adding the return-regression term raised behaviour success from 21% to 36% and sped up learning. Multi-step TD with four steps hurt (22% against 41%). A long ramp-in of the critic term, scaled with , stopped a decline we had seen on a long-horizon setting.
  • The critic recipe was the largest lever. QF3's reference run solved our main development setting, but at about six times our wall-clock time. To find out why, we moved QF3's actor into our fast loop. With our critic it collapsed (25%); with OGPO's critic settings it reached 78%. Taking those settings apart, a slow critic learning rate of alone lifted a short run from 37.5% to 53%. The fast target rate of 0.05 alone hurt (34% against 53%). OGPO's tapered stochastic behaviour sampler raised our development AUC from 0.27 to 0.45 on a short run. The slow critic and the stochastic sampler became defaults.
  • The larger, faster critic needs evidence. The 10-member, fast-target bundle helped where successes were common. Where they were rare it was much worse (3% against 22%), so it went behind a gate. Our first gate statistic, the episode success rate of the first rollouts, misfired on small samples (3 successes in 19 episodes). The share of steps in successful episodes separated the cases cleanly, and is what the code uses. A critic learning rate of helped on short effective horizons and hurt on long ones, so it too became a function of .
  • Stronger success imitation, gated. Late in the run, improved the scarce-success setting in all four paired comparisons we made. On a setting where successes were common it cost about 0.067 in development AUC at the same final success. We adopted it only on the scarce-evidence branch of the existing gate.
  • Things that trusted the critic further all failed. A larger best-of-N pool (24 candidates) fell from 47% to 31%, which we read as a winner's curse. A critic-gated residual head that the critic scored 18% better took actual paired success from 25% to 0%. Choosing the decoder by critic score preferred zero-noise decoding by tiny margins, and those deployments then collapsed. An OGPO-style likelihood-ratio actor over sampled chains ended at 40.6% on a short run and was not adopted. Episodic latent exploration, optimistic candidate scoring, TD on the success buffer, a raw instead of success-indicator reward, a shorter discount, and a higher actor learning-rate floor also failed to help.

Limitations

  • Not ahead of the field. On every setting at least two published baselines have a higher AUC. On ToolHang-PH HCQF is behind five, including the OGPO method it replaced. On Transport-MH it is behind that method on both metrics.
  • Thresholds fitted to development statistics. The horizon cut and the evidence gate at a share of 0.10 were set to separate the settings we developed on. In our own runs the gate statistic on one setting landed on both sides of the threshold (about 0.095 and 0.121), so the same setting can take either critic regime from one run to the next. We validated both branches there, but a new problem could fall on the wrong side of either rule.
  • The last change was the least tested. The scarce-evidence increase of was put into the gate at the very end. The longer end-to-end runs of the edited file had not reported; the evidence for it comes from earlier runs that set the weight by configuration.
  • Development evidence is noisy. Our development comparisons rest on small evaluation samples and few seeds. The trace itself reports that the same pretrained policy scored very differently across evaluation processes on one setting. Several of the ablation differences above are within that noise.
  • Many coupled parts. The method stacks a proxy, an anchor, two flow-matching terms, a scaled and ramped critic term, a calibrated critic, a stochastic sampler, best-of-8 behaviour and a gate. The ablations were run one change at a time on a moving baseline. We cannot say how much of the final result each part carries, and the file still contains two unused actor modes.

References

  1. Allen Z. Ren, Justin Lidard, Lars L. Ankile et al. (2025). Diffusion Policy Policy Optimization. ICLR.
  2. David McAllister, Songwei Ge, Brent Yi et al. (2026). Flow Matching Policy Gradients. ICLR.
  3. Tonghe Zhang, Chao Yu, Sichang Su et al. (2025). ReinFlow: Fine-tuning Flow Matching Policy with Online Reinforcement Learning. NeurIPS.
  4. Brent Yi, Hongsuk Choi, Himanshu Gaurav Singh et al. (2026). Flow Policy Gradients for Robot Control. CoRL.
  5. Seohong Park, Qiyang Li, Sergey Levine (2025). Flow Q-Learning. ICML.
  6. Qiyang Li, Zhiyuan Zhou, Sergey Levine (2025). Reinforcement Learning with Action Chunking. NeurIPS.
  7. Chung Min Kim, Brent Yi, David McAllister et al. (2026). QF3: Fast Flow RL with Filtered Q-Gradients.
  8. Andrew Wagenmaker, Mitsuhiko Nakamoto, Yunchu Zhang et al. (2025). Steering Your Diffusion Policy with Latent Space Reinforcement Learning. CoRL.
  9. Sarvesh Patil, Mitsuhiko Nakamoto, Manan Agarwal et al. (2026). OGPO: Sample Efficient Full-Finetuning of Generative Control Policies. ICML.
  10. Junhyuk Oh, Yijie Guo, Satinder Singh et al. (2018). Self-Imitation Learning. ICML.
  11. Haozhe Jiang, Haiwen Feng, Pieter Abbeel et al. (2026). DiPOD: Diffusion Policy Optimization without Drifting Apart.
  12. Lei Lv, Yunfei Li, Yu Luo et al. (2025). Flow-Based Policy for Online Reinforcement Learning. NeurIPS.
  13. Yixian Zhang, Shu'ang Yu, Tonghe Zhang et al. (2026). SAC Flow: Sample-Efficient Reinforcement Learning of Flow-Based Policies via Velocity-Reparameterized Sequential Modeling. ICLR.
  14. Charles Xu, Jacob Berg, Liyiming Ke et al. (2026). GSBR: Geometric Support Behavior Regularization for Online RL.

The session

The run from the model's first output, drawn as Muse Code shows a conversation: 806 steps.

Open the session

The submitted code

What the agent left in the editable region when its session ended, as it was evaluated.

OGPO_public/taskrt_custom.pythe changes against the starter, inside the editable region