AI Wiki中文/EN

Constitutional AI: principles shape revisions and preferences

宪法式 AI

Trace supervised revision and preference learning in an explicitly rule-based analogue.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A rule can change the training data before it changes the model

Consider four authored answers to “What is two plus two?”: a confident wrong answer, a correct wordy answer, a correct short answer and an unnecessary refusal. “Be brief” favors more than one of them, including the wrong answer. “Be accurate” and “be helpful” introduce other distinctions. Choosing the principles is already choosing what the training process should value.

Constitutional AI uses explicit principles to guide model-generated critiques, revisions and preference feedback. Bai and colleagues, sections 3–4, describe two stages: supervised learning from revised responses, followed by reinforcement learning using a preference model trained partly from AI judgments. Their original work uses AI labels for harmlessness while retaining human helpfulness labels. It is not a pipeline without human choices or human-derived data.

The example below exposes these stages with four answer IDs and handwritten rules. It is an executable analogy, not a language model that understands a constitution. Lee and colleagues, section 2, provide the broader distinction between AI feedback distilled into a reward model and AI feedback used directly as reward.

Explicit arithmetic rewrite rules and synthetic principle judgments illustrate two distinct learning stages.
Explicit arithmetic rewrite rules and synthetic principle judgments illustrate two distinct learning stages.

A principle can supervise a revision or a comparison

Let xx be a prompt, yky_k the current answer, and ckc_k a selected principle. The supervised data-building process can be represented as:

zk=C(x,yk,ck),yk+1=V(x,yk,zk,ck).z_k=C(x,y_k,c_k),\qquad y_{k+1}=V(x,y_k,z_k,c_k).

Here CC produces a critique and VV a revision. In the original work these are prompted language-model operations, and principles are sampled across revision steps. In our finite analogue they are explicit lookup rules. Generating a critique is not a proof that the critique is correct.

Once prompt–revision pairs have been assembled, supervised learning fits them:

LSL=−E(x,y~)∼Drevisionlog⁡πθ(y~∣x).\mathcal L_{\mathrm{SL}}=-\mathbb E_{(x,\widetilde y)\sim D_{\mathrm{revision}}}\log\pi_\theta(\widetilde y\mid x).

Bai, section 3.1, also mixes helpfulness responses into this stage. The resulting model is called SL-CAI in that paper. Merely attaching principles to a deployed prompt is a different intervention from this training procedure.

In the feedback stage, a judge compares two answers under a principle. If its log scores for the two option labels are ℓA,ℓB\ell_A,\ell_B, a soft preference target is:

tc(A≻B)=eℓAeℓA+eℓB.t_c(A\succ B)=\frac{e^{\ell_A}}{e^{\ell_A}+e^{\ell_B}}.

This normalization concerns the two scored options. It should not be confused with the probability that a response is universally acceptable. Option-order bias, ambiguous instructions and poorly calibrated confidence can affect it. Bai, section 4.1, reports clamping one chain-of-thought variant’s targets to 40–60%; that is a particular experimental choice, not a universal calibration guarantee.

A principle mixture requires specifying what is averaged. For weights wc≥0w_c\ge0 summing to one:

t‾ij=∑cwcσ(rc,i−rc,j)≠σ ⁣(∑cwc(rc,i−rc,j))in general.\overline t_{ij}=\sum_c w_c\sigma(r_{c,i}-r_{c,j})\ne\sigma\!\left(\sum_cw_c(r_{c,i}-r_{c,j})\right)\quad\text{in general}.

Our program averages probabilities from three synthetic principle score tables. This is a transparent design choice. The original paper samples principles for comparison labels; the toy’s exhaustive equal-weight averaging is not presented as that exact data-generation procedure.

A preference model can then fit the resulting soft labels, with sij=σ(ri−rj)s_{ij}=\sigma(r_i-r_j):

LR=−1N∑(i,j)[t‾ijlog⁡sij+(1−t‾ij)log⁡(1−sij)].\mathcal L_R=-\frac1N\sum_{(i,j)}[\overline t_{ij}\log s_{ij}+(1-\overline t_{ij})\log(1-s_{ij})].

Mixtures of preference models need not themselves be exactly representable by a single scalar Bradley–Terry model. We optimize the loss and inspect its gradient rather than claiming zero fitting error. Reward fitting is separate from the supervised revision stage.

For our finite action set, the subsequent KL-regularized policy has an exact solution:

pi=qieri/β∑jqjerj/β.p_i=\frac{q_i e^{r_i/\beta}}{\sum_jq_j e^{r_j/\beta}}.

Here qq is the supervised policy. The program uses this oracle instead of an RL optimizer, so it illustrates the reward-driven policy change without implementing the original paper’s full reinforcement-learning stage.

Make every rule and judgment visible

There are 12 initial responses with counts (6,2,2,2). The accuracy rule maps answer 0 to answer 1; brevity maps 1 to 2; helpfulness maps refusal 3 to 2. With all rules applied in that order, all 12 revisions are answer 2. Omitting accuracy leaves answer 0 wrong. The deterministic rule trace stands in for critique and revision; it does not generate natural-language reasoning.

To obtain a strictly positive reference distribution, the toy adds one pseudocount to each answer:

qitarget=ni+1∑jnj+4.q_i^{\mathrm{target}}=\frac{n_i+1}{\sum_j n_j+4}.

This smoothing is our teaching choice, not a claimed CAI recipe. A real softmax model’s learned probabilities are not generally empirical frequencies. Here we train four logits against the smoothed frequency target and can check the solution exactly.

"""A rule-based teaching analogue, NOT a language model or Constitutional AI reproduction."""
import json
import numpy as np


def sigmoid(x):
    x = np.asarray(x, dtype=float)
    return np.exp(-np.logaddexp(0, -x))


def softmax(x):
    x = np.asarray(x, dtype=float)
    if x.ndim != 1 or not len(x) or not np.isfinite(x).all():
        raise ValueError("Expected a nonempty finite vector")
    e = np.exp(x - x.max())
    return e / e.sum()


def preferences(scores, pairs):
    return sigmoid(scores[pairs[:, 0]] - scores[pairs[:, 1]])


def pair_loss_grad(scores, pairs, targets):
    scores = np.asarray(scores, dtype=float)
    pairs = np.asarray(pairs, dtype=int)
    targets = np.asarray(targets, dtype=float)
    if (scores.ndim != 1 or pairs.ndim != 2 or pairs.shape[1] != 2
        or len(pairs) == 0 or targets.shape != (len(pairs),)
        or not np.isfinite(scores).all() or not np.isfinite(targets).all()
        or np.any((targets < 0) | (targets > 1))
        or pairs.min() < 0 or pairs.max() >= len(scores)):
        raise ValueError("Invalid scores, pairs or soft labels")
    delta = scores[pairs[:, 0]] - scores[pairs[:, 1]]
    loss = np.mean(np.logaddexp(0, delta) - targets * delta)
    residual = (sigmoid(delta) - targets) / len(pairs)
    gradient = np.zeros_like(scores)
    np.add.at(gradient, pairs[:, 0], residual)
    np.add.at(gradient, pairs[:, 1], -residual)
    return float(loss), gradient


def fit_scores(pairs, targets, size=3, steps=2000):
    scores = np.zeros(size)
    for _ in range(steps):
        _, gradient = pair_loss_grad(scores, pairs, targets)
        scores -= 0.5 * gradient
    return scores


def policy_for_reward(reference, reward, beta):
    reference = np.asarray(reference, dtype=float)
    reward = np.asarray(reward, dtype=float)
    if (reference.ndim != 1 or reference.shape != reward.shape
        or not np.isfinite(reference).all() or not np.isfinite(reward).all()
        or np.any(reference <= 0) or not np.isclose(reference.sum(), 1)
        or not np.isfinite(beta) or beta <= 0):
        raise ValueError("Positive normalized reference and beta are required")
    return softmax(np.log(reference) + reward / beta)


PAIRS = np.array([[0, 1], [1, 2], [0, 2]])


# Four authored answers to 2+2: wrong, correct-wordy, correct-concise, abstention.
ANSWERS = ["5", "Adding two and two gives four.", "4", "I cannot answer."]
PRINCIPLES = np.array([[-2.,1.,1.,0.], [1.,-1.,1.,1.], [0.,1.,1.,-1.]])


def revise(answer, principles=("accuracy","brevity","helpfulness")):
    if answer not in range(4): raise ValueError("Unknown answer ID")
    transitions = {"accuracy":{0:1}, "brevity":{1:2}, "helpfulness":{3:2}}
    history = [answer]
    for name in principles:
        if name not in transitions: raise ValueError("Unknown principle")
        answer = transitions[name].get(answer,answer)
        history.append(answer)
    return answer, history


def sft_fit(counts, steps=1500):
    counts = np.asarray(counts,dtype=float)
    if counts.shape!=(4,) or not np.isfinite(counts).all() or np.any(counts<0) or counts.sum()<=0:
        raise ValueError("Four nonnegative counts are required")
    # One pseudocount per answer keeps the reference strictly positive.
    target = (counts+1)/(counts.sum()+4)
    logits=np.zeros(4)
    for _ in range(steps): logits -= .5*(softmax(logits)-target)
    return softmax(logits),target


def demo():
    initial=np.array([0]*6+[1]*2+[2]*2+[3]*2)
    revised=[revise(int(a))[0] for a in initial]
    counts=np.bincount(revised,minlength=4)
    reference,target=sft_fit(counts)
    pairs=np.array([[i,j] for i in range(4) for j in range(i+1,4)])
    # Average preference probabilities, NOT sigmoid of averaged scores.
    labels=np.mean([preferences(s,pairs) for s in PRINCIPLES],axis=0)
    reward=fit_scores(pairs,labels,size=4)
    policy=policy_for_reward(reference,reward,1.)
    return dict(answers=ANSWERS, initial_counts=np.bincount(initial,minlength=4).tolist(),
        revision_counts=counts.tolist(), example_history=revise(0)[1],
        omitted_accuracy=revise(0,("brevity","helpfulness"))[0],
        reference=reference.tolist(), smoothed_target=target.tolist(),
        pairs=pairs.tolist(), principle_labels=labels.tolist(), reward=reward.tolist(),
        policy=policy.tolist(),
        prefer_wrong_if_brevity_only=float(preferences(PRINCIPLES[1],np.array([[0,1]]))[0]),
        mixture_vs_mean_max_difference=float(np.max(abs(labels-preferences(PRINCIPLES.mean(axis=0),pairs)))))


if __name__ == "__main__":
    print(json.dumps(demo(), indent=2))

The supervised target is (1,1,13,1)/16, and gradient descent recovers it to numerical precision. After synthetic principle feedback is fitted, the KL-optimal policy assigns answer 2 probability about 0.90358468, compared with 0.8125 after supervised learning. This change is a result inside the authored rule system, not a measured safety improvement.

The maximum difference between averaging principle probabilities and applying sigmoid to averaged score differences is about 0.0635139. Under brevity alone, the wrong short answer beats the correct wordy answer with probability about 0.880797. The example makes the value choice inspectable instead of concealing it behind a single score.

For MM responses and CC rules, revision costs O(MC)O(MC). Exhaustive preference generation across KK answers costs O(CK2)O(CK^2); the toy uses only K=4K=4. Reward fitting is O(N+K)O(N+K) per update. Natural-language judge calls, model training and evaluation are absent from these costs.

Writing a principle does not settle its interpretation

A principle can be vague, conflict with another principle, or be applied inconsistently. A critique may sound plausible while missing the actual error. A feedback model may prefer refusal or familiar wording instead of satisfying the intended request. Separate evaluation should examine those behaviors rather than equating agreement with a judge to universal correctness.

The original system’s human-written principles, red-team prompts and helpfulness feedback remain substantive inputs. AI-generated labels change the supervision source; they do not remove decisions about whose interests, language or norms are represented. Updating a constitution should therefore preserve its version and the evaluation conditions, just as updating a dataset should.

This four-answer analogy has no open-ended language, real harmfulness task or independent evaluator. It shows how revisions and comparisons influence training, not how reliably a deployed model follows principles.

Change one principle and predict the result

  1. Remove the accuracy rule from the toy. What happens to an initial answer “5”?

Answer: It stays answer 0. Neither the brevity nor helpfulness transition corrects it; a shorter answer is not necessarily a better answer.

  1. Why is the supervised target’s largest probability 13/1613/16, not 1?

Answer: All 12 revised responses are answer 2, but one pseudocount is added to each of four answers. Its count becomes 13 out of 16. This is explicit smoothing, not evidence that three other responses appeared in the revisions.

  1. May we average principle scores first and expect the same preference labels?

Answer: No. Sigmoid is nonlinear. This example’s largest discrepancy is about 0.0635139; decide and document which mixture is intended.

  1. The final policy favors the correct short answer more often. Has the program reproduced the original paper’s harmlessness result?

Answer: No. It uses four arithmetic answers, authored transitions, synthetic judgments and an exact policy oracle. It tests the mechanics of the analogy, without a language model, human evaluation or the original training experiment.

Read both stages, not just the principle list

Bai’s sections 3 and 4 distinguish supervised revision from preference-based reinforcement learning. Lee’s section 2 places AI feedback in a wider family that also includes direct scoring. Comparing such systems requires the principle version, label source, policy-training method and an evaluation independent of the training judge.

Make a prediction, then check

Does Constitutional AI remove all human choices from training?

Choose one answer

Learning objectives

  • Separate principles, revised demonstrations and AI comparison labels.
  • Verify the toy calculation and state what it cannot establish.

Prerequisites & connections

Explore related knowledge →

References

  1. Constitutional AI: Harmlessness from AI Feedback — v1
    Yuntao Bai and coauthors · 2022
  2. RLAIF: Scaling Reinforcement Learning from Human Feedback with AI Feedback — v2
    Harrison Lee; Samrat Phatale; Hassan Mansoor; Thomas Mesnard; Johan Ferret; Kellie Lu; Colton Bishop; Ethan Hall; Victor Carbune; Abhinav Rastogi; Sushant Prakash · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Sections3.1/3.2 and4.1/4.2 opening; PDF7/10/11 viewed. Critique/revision, supervised stage, AI harmlessness plus human helpfulness labels and soft preference targets. Sections2.1.1/2.1.2/2.2,2.3 opening and4.3/4.4 text; PDF3/4 viewed. Order balancing, distilled/direct feedback and separate evaluation metrics; v2 dated2023-12-01. Seven paired equations and four explained exercises. Original paper retains human helpfulness labels. Rule-based arithmetic analogy separates revisions, smoothed SFT, mixed soft labels and an exact policy oracle; no actual CAI model or safety benchmark.

  • Original paper retains human helpfulness labels. Rule-based arithmetic analogy separates revisions, smoothed SFT, mixed soft labels and an exact policy oracle; no actual CAI model or safety benchmark.
  • Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.