.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/03_evaluators/plot_02_llm_judge.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_03_evaluators_plot_02_llm_judge.py: An AI judge in the loop: prompts, images and debiasing ====================================================== :class:`~easyiec.evaluators.LLMJudge` turns a query into a prompt for a language or vision–language model: the goal, the protocol, the candidates as labelled images (or text), and a JSON schema for the answer. Because LLM judges prefer the first or the second option more often than chance (Zheng et al., 2023; Shi et al., 2024), the judge can ask several times with the candidates in reversed or permuted order and aggregate the answers. Here the model is the offline :class:`~easyiec.evaluators.MockJudgeClient`, whose taste and biases we control; with an API key the same code runs with Claude (see the last section of the gallery). .. GENERATED FROM PYTHON SOURCE LINES 17-19 What the model receives ----------------------- .. GENERATED FROM PYTHON SOURCE LINES 19-40 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import easyiec as ei from easyiec.evaluators import LLMJudge, MockJudgeClient from easyiec.imaging import decode_png from easyiec.problems import JuliaSet from easyiec.strategies import InteractiveGA from easyiec.validation import make_individuals problem = JuliaSet() target = problem.random(np.random.default_rng(5)) taste = lambda g: problem.utility(g, target) # noqa: E731 the mock judge's hidden taste client = MockJudgeClient(scorer=taste, score_on="genome", noise=0.05, position_bias=0.05, seed=1) judge = LLMJudge(client, problem, goal="an intricate, glowing spiral in cool colours", debias="reverse", n_views=2, image_size=128) items = make_individuals(problem.random(np.random.default_rng(0), 6)) fb = judge.evaluate(ei.Query("select", items, n_select=2)) print(fb.summary()) print("rationale:", fb.rationale[:120]) print("uncertainty:", fb.uncertainty, " cost:", fb.cost) .. rst-class:: sphx-glr-script-out .. code-block:: none select by llm:mock-judge, selected=[10003211, 10003207], uncertainty=0.67 rationale: mock judgment based on the scorer | mock judgment based on the scorer uncertainty: 0.6666666666666667 cost: {'tokens_in': 2512, 'tokens_out': 46, 'usd': 0.0, 'calls': 2, 'seconds': 0.3929481506347656, 'decisions': 6} .. GENERATED FROM PYTHON SOURCE LINES 41-43 The two requests of the last answer: the system prompt, the instruction and the composite image, once in the original and once in reversed order. .. GENERATED FROM PYTHON SOURCE LINES 43-52 .. code-block:: Python views = client.requests[-2:] print(views[0].system[:300], "...") print("\n".join(v for k, v in views[0].parts if k == "text")[:900], "...") fig, axes = plt.subplots(1, 2, figsize=(9, 3.4)) for ax, req, title in zip(axes, views, ["first view", "second view (order reversed)"]): ax.imshow(decode_png(next(v for k, v in req.parts if k == "image"))) ax.set_title(title, fontsize=9) ax.axis("off") .. image-sg:: /auto_examples/03_evaluators/images/sphx_glr_plot_02_llm_judge_001.png :alt: first view, second view (order reversed) :srcset: /auto_examples/03_evaluators/images/sphx_glr_plot_02_llm_judge_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none You are a careful evaluator in an interactive evolutionary computation session. Candidates generated by an optimization algorithm are shown to you, and your judgments decide which candidates survive and reproduce. Judge every candidate only against the stated goal and criteria. Ignore the order in w ... The image shows 6 candidates; each tile carries its label in the top-left corner. Task: Julia set. Each candidate is a coloured Julia set fractal image. Goal: an intricate, glowing spiral in cool colours The candidates are labelled 1, 2, 3, 4, 5, 6 (labels are arbitrary; their order carries no meaning). Look at all images before deciding. Choose exactly 2 candidate(s) that best satisfy the goal. Reply as JSON: {"rationale": "", "selected": [], "confidence": }. ... .. GENERATED FROM PYTHON SOURCE LINES 53-61 Position bias and what reversal buys ------------------------------------ A judge whose first-shown option gets a bonus of 0.1 on the utility scale is asked about 80 pairs, once (``debias="none"``) or twice in both orders. Asked once, it prefers the first option far more often than half of the time. Reversal cannot make the judge see better; it removes the systematic preference and turns order-dependent verdicts into ties with high uncertainty — exactly the cases a hybrid evaluator should pass to a person. .. GENERATED FROM PYTHON SOURCE LINES 61-84 .. code-block:: Python pairs = [make_individuals(problem.random(np.random.default_rng(100 + k), 2)) for k in range(80)] truth = np.array([taste(a.genome) > taste(b.genome) for a, b in pairs]) stats = {} for mode in ["none", "reverse"]: j = LLMJudge(MockJudgeClient(scorer=taste, score_on="genome", noise=0.05, position_bias=0.1, seed=2), problem, debias=mode, image_size=48) r = np.array([j.evaluate(ei.Query("pairs", [a, b])).pair_results[0][2] for a, b in pairs]) decided = r != 0.5 stats[mode] = {"first option chosen": np.mean(r[decided] > 0.5), "accuracy (decided pairs)": np.mean((r[decided] > 0.5) == truth[decided]), "flagged as tie": 1 - decided.mean()} print(stats) fig, ax = plt.subplots(figsize=(6.4, 3)) keys = list(stats["none"]) x = np.arange(len(keys)) ax.bar(x - 0.18, [stats["none"][k] for k in keys], 0.36, label="asked once", color="#D55E00") ax.bar(x + 0.18, [stats["reverse"][k] for k in keys], 0.36, label="both orders", color="#285780") ax.axhline(truth.mean(), color="0.6", lw=0.8, ls="--") ax.text(2.45, truth.mean() + 0.02, "true share of\nfirst-better pairs", fontsize=7, color="0.4", ha="right") ax.set_xticks(x, keys, fontsize=8) ax.legend(frameon=False, fontsize=8) ax.set_title("a position-biased judge, 80 pairs", fontsize=9) .. image-sg:: /auto_examples/03_evaluators/images/sphx_glr_plot_02_llm_judge_002.png :alt: a position-biased judge, 80 pairs :srcset: /auto_examples/03_evaluators/images/sphx_glr_plot_02_llm_judge_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none {'none': {'first option chosen': np.float64(0.5625), 'accuracy (decided pairs)': np.float64(0.8875), 'flagged as tie': np.float64(0.0)}, 'reverse': {'first option chosen': np.float64(0.39285714285714285), 'accuracy (decided pairs)': np.float64(0.9821428571428571), 'flagged as tie': np.float64(0.30000000000000004)}} Text(0.5, 1.0, 'a position-biased judge, 80 pairs') .. GENERATED FROM PYTHON SOURCE LINES 85-87 The judge drives a whole session -------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 87-91 .. code-block:: Python res = ei.run(problem, InteractiveGA(pop_size=9), judge, generations=10, seed=1, oracle=taste) ei.viz.plot_anytime(res, label="mock LLM judge") print(res.summary()) plt.show() .. image-sg:: /auto_examples/03_evaluators/images/sphx_glr_plot_02_llm_judge_003.png :alt: plot 02 llm judge :srcset: /auto_examples/03_evaluators/images/sphx_glr_plot_02_llm_judge_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none {'problem': 'julia', 'strategy': 'InteractiveGA', 'evaluator': 'llm:mock-judge', 'queries': 10, 'items': 90, 'human': 0, 'usd': 0.0, 'best_true': 0.8951487567863271, 'stopped': 'max_generations', 'seed': 1} .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 12.897 seconds) .. _sphx_glr_download_auto_examples_03_evaluators_plot_02_llm_judge.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/ComplexSystemsIntelligence/easyiec/main?urlpath=lab/tree/notebooks/auto_examples/03_evaluators/plot_02_llm_judge.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_02_llm_judge.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_02_llm_judge.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_02_llm_judge.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_