πŸ“„ Sound ReasoningΒΆ

cards.judge_bench.inferential_strategies.sound_reasoning

TaskCard(
    loader=LoadJsonFile(
        files={
            "test": "https://raw.githubusercontent.com/dmg-illc/JUDGE-BENCH/refs/heads/master/data/inferential-strategies/inferential_strategies.json",
        },
        data_classification_policy=[
            "public",
        ],
        data_field="instances",
    ),
    preprocess_steps=[
        GroupDictWithRegex(
            field="instance",
            pattern=".*?### PROBLEM STATEMENT\s+(?P<problem_statement>.*?)\s+Statements:\s+(?P<statements>.*?)\s+Let\'s think step by step\.\s*### MODEL RESPONSE\s+(?P<model_reasoning>.*)",
            flags=16,
        ),
        FilterByCondition(
            values={
                "instance/problem_statement": True,
            },
            condition="exists",
        ),
        Rename(
            field_to_field={
                "instance/problem_statement": "problem statement",
                "instance/statements": "statements",
                "instance/model_reasoning": "model reasoning",
                "annotations/Sound Reasoning/majority_human": "label",
            },
        ),
        MapInstanceValues(
            mappers={
                "label": {
                    "no": "No",
                    "yes": "Yes",
                },
            },
        ),
        Copy(
            field="label",
            to_field="label_value",
        ),
        MapInstanceValues(
            mappers={
                "label_value": {
                    "Yes": 1.0,
                    "No": 0.0,
                },
            },
        ),
        Set(
            fields={
                "criteria": "metrics.llm_as_judge.direct.criteria.logical_validity_of_reasoning",
            },
        ),
    ],
    task=Task(
        input_fields={
            "problem statement": "str",
            "statements": "str",
            "model reasoning": "str",
            "label": "str",
            "criteria": "Any",
        },
        reference_fields={
            "label_value": "float",
        },
        prediction_type="float",
        metrics=[
            "metrics.accuracy",
            "metrics.f1_macro",
        ],
        default_template="templates.empty[postprocessors=[processors.cast_to_float_return_nan_if_failed]]",
    ),
    templates=[],
)
[source]

from unitxt.loaders import LoadJsonFile
from unitxt.operators import Copy, FilterByCondition, MapInstanceValues, Rename, Set
from unitxt.processors import GroupDictWithRegex
from unitxt.task import Task

Explanation about TaskCardΒΆ

TaskCard delineates the phases in transforming the source dataset into model input, and specifies the metrics for evaluation of model output.

Args:
loader:

specifies the source address and the loading operator that can access that source and transform it into a unitxt multistream.

preprocess_steps:

list of unitxt operators to process the data source into model input.

task:

specifies the fields (of the already (pre)processed instance) making the inputs, the fields making the outputs, and the metrics to be used for evaluating the model output.

templates:

format strings to be applied on the input fields (specified by the task) and the output fields. The template also carries the instructions and the list of postprocessing steps, to be applied to the model output.

Explanation about GroupDictWithRegexΒΆ

Extracts named groups from a string using a regular expression pattern, returning a dictionary of group names to values.

Args:

pattern (str): A regular expression with named groups (using (?P<name>…)).

Example:
>>> op = GroupDictWithRegex(pattern=r"(?P<name>\\w+):(?P<age>\\d+)")
>>> op.process_value("alice:23")
{'name': 'alice', 'age': '23'}
>>> op.process_value("not_a_match")
{}
Returns:

dict: A dictionary mapping group names to matched values, or an empty dict if no match.

Explanation about TaskΒΆ

Task packs the different instance fields into dictionaries by their roles in the task.

Args:
input_fields (Union[Dict[str, str], List[str]]):

Dictionary with string names of instance input fields and types of respective values. In case a list is passed, each type will be assumed to be Any.

reference_fields (Union[Dict[str, str], List[str]]):

Dictionary with string names of instance output fields and types of respective values. In case a list is passed, each type will be assumed to be Any.

metrics (List[str]):

List of names of metrics to be used in the task.

prediction_type (Optional[str]):

Need to be consistent with all used metrics. Defaults to None, which means that it will be set to Any.

defaults (Optional[Dict[str, Any]]):

An optional dictionary with default values for chosen input/output keys. Needs to be consistent with names and types provided in β€˜input_fields’ and/or β€˜output_fields’ arguments. Will not overwrite values if already provided in a given instance.

The output instance contains three fields:
  1. β€œinput_fields” whose value is a sub-dictionary of the input instance, consisting of all the fields listed in Arg β€˜input_fields’.

  2. β€œreference_fields” – for the fields listed in Arg β€œreference_fields”.

  3. β€œmetrics” – to contain the value of Arg β€˜metrics’

Explanation about MapInstanceValuesΒΆ

A class used to map instance values into other values.

This class is a type of InstanceOperator, it maps values of instances in a stream using predefined mappers.

Args:
mappers (Dict[str, Dict[str, Any]]):

The mappers to use for mapping instance values. Keys are the names of the fields to undergo mapping, and values are dictionaries that define the mapping from old values to new values. Note that mapped values are defined by their string representation, so mapped values are converted to strings before being looked up in the mappers.

strict (bool):

If True, the mapping is applied strictly. That means if a value does not exist in the mapper, it will raise a KeyError. If False, values that are not present in the mapper are kept as they are.

process_every_value (bool):

If True, all fields to be mapped should be lists, and the mapping is to be applied to their individual elements. If False, mapping is only applied to a field containing a single value.

Examples:

MapInstanceValues(mappers={"a": {"1": "hi", "2": "bye"}}) replaces "1" with "hi" and "2" with "bye" in field "a" in all instances of all streams: instance {"a": 1, "b": 2} becomes {"a": "hi", "b": 2}. Note that the value of "b" remained intact, since field-name "b" does not participate in the mappers, and that 1 was casted to "1" before looked up in the mapper of "a".

MapInstanceValues(mappers={"a": {"1": "hi", "2": "bye"}}, process_every_value=True): Assuming field "a" is a list of values, potentially including "1"-s and "2"-s, this replaces each such "1" with "hi" and "2" – with "bye" in all instances of all streams: instance {"a": ["1", "2"], "b": 2} becomes {"a": ["hi", "bye"], "b": 2}.

MapInstanceValues(mappers={"a": {"1": "hi", "2": "bye"}}, strict=True): To ensure that all values of field "a" are mapped in every instance, use strict=True. Input instance {"a":"3", "b": 2} will raise an exception per the above call, because "3" is not a key in the mapper of "a".

MapInstanceValues(mappers={"a": {str([1,2,3,4]): "All", str([]): "None"}}, strict=True) replaces a list [1,2,3,4] with the string "All" and an empty list by string "None".

Explanation about FilterByConditionΒΆ

Filters a stream, yielding only instances in which the values in required fields follow the required condition operator.

Raises an error if a required field name is missing from the input instance.

Args:

values (Dict[str, Any]): Field names and respective Values that instances must match according the condition, to be included in the output.

condition: the name of the desired condition operator between the specified (sub) field’s value and the provided constant value. Supported conditions are (β€œgt”, β€œge”, β€œlt”, β€œle”, β€œne”, β€œeq”, β€œin”,”not in”)

error_on_filtered_all (bool, optional): If True, raises an error if all instances are filtered out. Defaults to True.

Examples:
FilterByCondition(values = {"a":4}, condition = "gt") will yield only instances where field "a" contains a value > 4
FilterByCondition(values = {"a":4}, condition = "le") will yield only instances where "a"<=4
FilterByCondition(values = {"a":[4,8]}, condition = "in") will yield only instances where "a" is 4 or 8
FilterByCondition(values = {"a":[4,8]}, condition = "not in") will yield only instances where "a" is different from 4 or 8
FilterByCondition(values = {"a/b":[4,8]}, condition = "not in") will yield only instances where "a" is a dict in which key "b" is mapped to a value that is neither 4 nor 8
FilterByCondition(values = {"a[2]":4}, condition = "le") will yield only instances where β€œa” is a list whose 3-rd element is <= 4
FilterByCondition(values = {"a":False}, condition = "exists") will yield only instances which do not contain a field named "a"
FilterByCondition(values = {"a/b":True}, condition = "exists") will yield only instances which contain a field named "a" whose value is a dict containing, in turn, a field named "b"

Explanation about RenameΒΆ

Renames fields.

Move value from one field to another, potentially, if field name contains a /, from one branch into another. Remove the from field, potentially part of it in case of / in from_field.

Examples:

Rename(field_to_field={β€œb”: β€œc”}) will change inputs [{β€œa”: 1, β€œb”: 2}, {β€œa”: 2, β€œb”: 3}] to [{β€œa”: 1, β€œc”: 2}, {β€œa”: 2, β€œc”: 3}]

Rename(field_to_field={β€œb”: β€œc/d”}) will change inputs [{β€œa”: 1, β€œb”: 2}, {β€œa”: 2, β€œb”: 3}] to [{β€œa”: 1, β€œc”: {β€œd”: 2}}, {β€œa”: 2, β€œc”: {β€œd”: 3}}]

Rename(field_to_field={β€œb”: β€œb/d”}) will change inputs [{β€œa”: 1, β€œb”: 2}, {β€œa”: 2, β€œb”: 3}] to [{β€œa”: 1, β€œb”: {β€œd”: 2}}, {β€œa”: 2, β€œb”: {β€œd”: 3}}]

Rename(field_to_field={β€œb/c/e”: β€œb/d”}) will change inputs [{β€œa”: 1, β€œb”: {β€œc”: {β€œe”: 2, β€œf”: 20}}}] to [{β€œa”: 1, β€œb”: {β€œc”: {β€œf”: 20}, β€œd”: 2}}]

Explanation about CopyΒΆ

Copies values from specified fields to specified fields.

Args (of parent class):

field_to_field (Union[List[List], Dict[str, str]]): A list of lists, where each sublist contains the source field and the destination field, or a dictionary mapping source fields to destination fields.

Examples:

An input instance {β€œa”: 2, β€œb”: 3}, when processed by Copy(field_to_field={"a": "b"}) would yield {β€œa”: 2, β€œb”: 2}, and when processed by Copy(field_to_field={"a": "c"}) would yield {β€œa”: 2, β€œb”: 3, β€œc”: 2}

with field names containing / , we can also copy inside the field: Copy(field="a/0",to_field="a") would process instance {β€œa”: [1, 3]} into {β€œa”: 1}

Explanation about SetΒΆ

Sets specified fields in each instance, in a given stream or all streams (default), with specified values. If fields exist, updates them, if do not exist – adds them.

Args:

fields (Dict[str, object]): The fields to add to each instance. Use β€˜/’ to access inner fields

use_deepcopy (bool) : Deep copy the input value to avoid later modifications

Examples:

# Set a value of a list consisting of β€œpositive” and β€œnegative” do field β€œclasses” to each and every instance of all streams Set(fields={"classes": ["positive","negatives"]})

# In each and every instance of all streams, field β€œspan” is to become a dictionary containing a field β€œstart”, in which the value 0 is to be set Set(fields={"span/start": 0}

# In all instances of stream β€œtrain” only, Set field β€œclasses” to have the value of a list consisting of β€œpositive” and β€œnegative” Set(fields={"classes": ["positive","negatives"], apply_to_stream=["train"]})

# Set field β€œclasses” to have the value of a given list, preventing modification of original list from changing the instance. Set(fields={"classes": alist}), use_deepcopy=True) if now alist is modified, still the instances remain intact.

Explanation about LoadJsonFileΒΆ

Loads data from JSON files.

Supports streaming and can handle large files by loading them in chunks.

Args:

files (Dict[str, str]): A dictionary mapping names to file paths. chunksize : Size of the chunks to load at a time. loader_limit: Optional integer to specify a limit on the number of records to load. streaming: Bool indicating if streaming should be used. lines: Bool indicate if it is json lines file structure. Otherwise, assumes a single json object in the file. data_field: optional field within the json object, that contains the list of instances.

Example:

Loading json lines

load_csv = LoadJsonFile(files={'train': 'path/to/train.jsonl'}, line=True, chunksize=100)

References: metrics.llm_as_judge.direct.criteria.logical_validity_of_reasoning, processors.cast_to_float_return_nan_if_failed, metrics.f1_macro, metrics.accuracy, templates.empty

Read more about catalog usage here.