

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Personnalisation de modèles avec Amazon AI SageMaker
<a name="customize-model"></a>

La personnalisation des modèles d' SageMaker IA d'Amazon est une fonctionnalité qui transforme le processus traditionnellement complexe et fastidieux de personnalisation des modèles d'IA en un flux de travail rationalisé pouvant être réalisé en quelques jours. Cette fonctionnalité répond au défi critique auquel sont confrontés les développeurs d'IA qui doivent personnaliser les modèles de base à l'aide de données propriétaires afin de créer des expériences client hautement différenciées. Une documentation de personnalisation détaillée, y compris step-by-step des guides et des options de configuration avancées, est fournie dans ce guide sur l' SageMaker IA. Pour un bref aperçu de la personnalisation des modèles Nova, consultez la section [Personnaliser et peaufiner avec SageMaker](https://docs.aws.amazon.com/nova/latest/userguide/customize-fine-tune-sagemaker.html) dans le guide de l'utilisateur Amazon Nova.

Cette fonctionnalité inclut une nouvelle interface utilisateur guidée qui comprend les exigences du langage naturel, ainsi qu'une suite complète de techniques avancées de personnalisation des modèles, le tout alimenté par une infrastructure sans serveur qui élimine les frais opérationnels liés à la gestion des ressources informatiques. Que vous développiez des applications de recherche juridique, que vous amélioriez les chatbots du service client ou que vous développiez des agents d'intelligence artificielle spécifiques à un domaine, cette fonctionnalité accélère votre passage proof-of-concept au déploiement en production.

Les fonctionnalités de personnalisation des modèles optimisées par Amazon Bedrock Evaluations peuvent transmettre des données en toute sécurité Régions AWS au sein de votre zone géographique à des fins de traitement. Pour plus d'informations, consultez la [documentation d'Amazon Bedrock Evaluations](https://docs.aws.amazon.com/bedrock/latest/userguide/evaluation-judge.html).

## Concepts clés
<a name="model-customize-concepts"></a>

**Formation sans serveur**

Une infrastructure informatique entièrement gérée qui élimine toute complexité de l'infrastructure, vous permettant de vous concentrer uniquement sur le développement de modèles. Cela inclut le provisionnement automatique des instances GPU (P5, P4de, P4d, G5) en fonction de la taille du modèle et des exigences de formation, des recettes de formation préoptimisées intégrant les meilleures pratiques pour chaque technique de personnalisation, une surveillance en temps réel avec des métriques en temps réel et des journaux accessibles via l'interface utilisateur, et le nettoyage automatique des ressources à la fin de la formation afin d'optimiser les coûts.

**Techniques de personnalisation des modèles**

Ensemble complet de méthodes avancées, notamment le réglage fin supervisé (SFT), l'optimisation directe des préférences (DPO), l'apprentissage par renforcement avec récompenses vérifiables (RLVR) et l'apprentissage par renforcement avec feedback basé sur l'IA (RLAIF).

**Modèle personnalisé**

Version spécialisée d'un modèle de base qui a été adaptée à un cas d'utilisation spécifique en l'entraînant sur vos propres données, ce qui a permis d'obtenir un modèle d'IA qui conserve les fonctionnalités générales du modèle de base d'origine tout en ajoutant des connaissances, une terminologie, un style ou un comportement spécifiques au domaine, adaptés à vos besoins.

**Ressources de personnalisation des modèles d'IA**

Ressources et artefacts utilisés pour entraîner, affiner et évaluer des modèles personnalisés au cours du processus de personnalisation des modèles. ***Ces actifs incluent des **ensembles** de données, qui sont des collections d'exemples d'entraînement (paires prompte-réponse, texte spécifique à un domaine ou données étiquetées) utilisés pour affiner un modèle de base afin d'apprendre des comportements, des connaissances ou des styles spécifiques, et des **évaluateurs**, qui sont des mécanismes permettant d'évaluer et d'améliorer les performances du modèle par le biais de ***fonctions de récompense*** (logique basée sur le code qui note les résultats du modèle en fonction de critères spécifiques, utilisée dans la formation RLVR et l'évaluation personnalisée des scores) ou des invites de récompense (*** instructions en langage naturel qui guident un LLM pour évaluer la qualité des réponses du modèle, utilisées dans le cadre de la formation et LLM-as-a-judge de l'évaluation du RLAIF).

**Groupe de packages modèles**

Un conteneur de collecte qui permet de suivre tous les modèles enregistrés lors des tâches de formation, fournissant un emplacement centralisé pour les versions des modèles et leur lignée.

**Modèle enregistré**

Résultat créé par l' SageMaker IA lors de l'exécution de tâches de formation sans serveur. Il peut s'agir d'un modèle affiné (tâche réussie), d'un point de contrôle (tâche échouée avec point de contrôle) ou de métadonnées associées (tâche échouée sans point de contrôle).

**Modèle enregistré**

Un modèle enregistré qui a été marqué à des fins formelles de suivi et de gouvernance, permettant une gestion complète du lignage et du cycle de vie.

**Lignée**

Les relations entre les tâches de formation, les ensembles de données d'entrée, les modèles de sortie, les tâches d'évaluation et les déploiements sur SageMaker AI et Amazon Bedrock ont été capturées automatiquement.

**Partage entre comptes**

Possibilité de partager des modèles, des ensembles de données et des évaluateurs entre AWS comptes à l'aide de AWS Resource Access Manager (RAM) tout en conservant une visibilité complète du lignage.

# Personnalisation des modèles Amazon Nova sur Amazon AI SageMaker
<a name="nova-model"></a>

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez la section Personnalisation des modèles Amazon Nova sur Amazon SageMaker AI dans le guide de l'[utilisateur Amazon Nova 1.0 ou le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-model.html) de l'[utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-model.html).

# Formules Amazon Nova
<a name="nova-model-recipes"></a>

Ce sujet a été déplacé. Pour obtenir les informations les plus récentes, consultez les recettes Amazon Nova dans le guide de [l'utilisateur Amazon Nova 1.0 ou dans le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-model-recipes.html) de [l'utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-model-recipes.html).

# Personnalisation d'Amazon Nova pour les tâches SageMaker de formation
<a name="nova-model-training-job"></a>

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez la section Personnalisation d'Amazon Nova pour les tâches de SageMaker formation dans le guide de [l'utilisateur Amazon Nova 1.0 ou le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-model-training-job.html) de [l'utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-model-training-job.html).

**Topics**
+ [Distillation Amazon Nova](nova-distillation.md)
+ [SDK de personnalisation Nova](nova-customization-sdk.md)
+ [Affiner les modèles Amazon Nova à l'aide de tâches SageMaker de formation](nova-fine-tuning-training-job.md)
+ [Suivi des progrès au fil des itérations](nova-model-monitor.md)
+ [Évaluation de votre modèle entraîné par SageMaker l'IA](nova-model-evaluation.md)

# Distillation Amazon Nova
<a name="nova-distillation"></a>

Ce sujet a été déplacé. Pour obtenir les informations les plus récentes, consultez Amazon Nova distillation dans le [guide de l'utilisateur d'Amazon Nova 1.0](https://docs.aws.amazon.com//nova/latest/userguide/nova-distillation.html).

# SDK de personnalisation Nova
<a name="nova-customization-sdk"></a>

Le SDK de personnalisation Amazon Nova est un SDK Python complet permettant de personnaliser les modèles Amazon Nova tout au long de leur cycle de vie, de la formation et de l'évaluation au déploiement et à l'inférence.

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez le SDK de personnalisation Nova dans le guide de l'[utilisateur Amazon Nova 1.0 ou dans le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-customization-sdk.html) de l'[utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-customization-sdk.html).

# Affiner les modèles Amazon Nova à l'aide de tâches SageMaker de formation
<a name="nova-fine-tuning-training-job"></a>

Ce sujet a été déplacé. Pour obtenir les informations les plus récentes, consultez la section Optimisation des modèles Amazon Nova à l'aide de tâches de SageMaker formation dans le guide de [l'utilisateur Amazon Nova 1.0 ou le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-fine-tune-1.html) de l'[utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/smtj-training.html).

# Suivi des progrès au fil des itérations
<a name="nova-model-monitor"></a>

Ce sujet a été déplacé. Pour obtenir les informations les plus récentes, consultez la section Surveillance de la progression entre les itérations dans le guide de [l'utilisateur Amazon Nova 1.0 ou le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-model-monitor.html) de l'[utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-model-monitor.html).

# Évaluation de votre modèle entraîné par SageMaker l'IA
<a name="nova-model-evaluation"></a>

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez la section Évaluation de votre modèle SageMaker entraîné par l'IA dans le guide de [l'utilisateur d'Amazon Nova 1.0 ou le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-model-evaluation.html) de l'[utilisateur d'Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-model-evaluation.html).

# Personnalisation d'Amazon Nova sur Amazon SageMaker HyperPod
<a name="nova-hp"></a>

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez la section Personnalisation d'Amazon Nova sur Amazon SageMaker HyperPod dans le guide de [l'utilisateur Amazon Nova 1.0 ou le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-hp.html) de [l'utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-hp.html).

# SDK de personnalisation Nova
<a name="nova-hp-customization-sdk"></a>

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez le SDK de personnalisation Nova dans le guide de l'[utilisateur Amazon Nova 1.0 ou dans le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-hp-customization-sdk.html) de l'[utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-hp-customization-sdk.html).

# Guide des commandes Amazon HyperPod Essential
<a name="nova-hp-essential-commands-guide"></a>

Ce sujet a été déplacé. Pour obtenir les informations les plus récentes, consultez le guide des commandes SageMaker HyperPod essentielles dans le guide de [l'utilisateur Amazon Nova 1.0 ou dans le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-hp-essential-commands-guide.html) de [l'utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-hp-essential-commands-guide.html).

# Création d'un cluster HyperPod EKS avec un groupe d'instances restreint (RIG)
<a name="nova-hp-cluster"></a>

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez la section Création d'un cluster SageMaker HyperPod EKS avec RIG dans le guide de [l'utilisateur Amazon Nova 1.0 ou le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-hp-cluster.html) de [l'utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-hp-cluster.html).

# Accès à Nova Forge et configuration pour l' SageMaker IA HyperPod
<a name="nova-forge-hp-access"></a>

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez la section Accès à Nova Forge et configuration pour l' SageMaker IA HyperPod dans le guide de [l'utilisateur Amazon Nova 1.0 ou le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-forge-hp-access.html) de [l'utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-forge-hp-access.html).

# Formation pour les modèles Amazon Nova
<a name="nova-hp-training"></a>

Ce sujet a été déplacé. Pour obtenir les informations les plus récentes, consultez la section Formation pour les modèles Amazon Nova dans le guide de [l'utilisateur Amazon Nova 1.0 ou dans le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-hp-training.html) de [l'utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-hp-training.html).

# Réglage précis des modèles Amazon Nova sur Amazon SageMaker HyperPod
<a name="nova-hp-fine-tune"></a>

Ce sujet a été déplacé. Pour obtenir les informations les plus récentes, consultez la section Réglage précis des modèles Amazon Nova sur Amazon SageMaker HyperPod dans le [guide de l'utilisateur Amazon Nova 1.0](https://docs.aws.amazon.com//nova/latest/userguide/nova-hp-fine-tune.html).

# Évaluation de votre modèle entraîné
<a name="nova-hp-evaluate"></a>

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez la section Évaluation de votre modèle entraîné dans le guide de l'[utilisateur d'Amazon Nova 1.0 ou le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-hp-evaluate.html) de l'[utilisateur d'Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-hp-evaluate.html).

# Entraînement itératif
<a name="nova-iterative-training"></a>

La formation itérative vous permet d'améliorer les performances des modèles grâce à plusieurs cycles de formation, en vous appuyant sur les points de contrôle précédents pour traiter systématiquement les modes de défaillance et vous adapter à l'évolution des exigences.

Ce sujet a été déplacé. Pour obtenir les informations les plus récentes, consultez la section Formation itérative du guide de [l'utilisateur Amazon Nova 1.0 ou du guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-iterative-training.html) de l'[utilisateur Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-iterative-training.html).

# Inférence Amazon Bedrock
<a name="nova-model-bedrock-inference"></a>

Ce sujet a été déplacé. Pour obtenir les informations les plus récentes, consultez l'inférence Amazon Bedrock dans le guide de [l'utilisateur d'Amazon Nova 1.0 ou dans le guide](https://docs.aws.amazon.com//nova/latest/userguide/nova-model-bedrock-inference.html) de l'[utilisateur d'Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-model-bedrock-inference.html).

# Limites liées à la personnalisation des modèles Amazon Nova
<a name="nova-model-limitations"></a>

Ce sujet a été déplacé. Pour obtenir les dernières informations, consultez la section Limitations relatives à la personnalisation des modèles Amazon Nova dans le [guide de l'utilisateur d'Amazon Nova 2.0](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-model-limitations.html).

# Personnalisation ouverte du modèle de poids
<a name="model-customize-open-weight"></a>

Cette section explique le processus de démarrage de la personnalisation des modèles à poids ouvert.

**Topics**
+ [Conditions préalables](model-customize-open-weight-prereq.md)
+ [Création de ressources pour la personnalisation des modèles dans l'interface utilisateur](model-customize-open-weight-create-assets-ui.md)
+ [Soumission de tâches de personnalisation de modèles d'IA](model-customize-open-weight-job.md)
+ [Soumission d'une tâche d'évaluation du modèle](model-customize-open-weight-evaluation.md)
+ [Déploiement de modèles](model-customize-open-weight-deployment.md)
+ [Exemples d'ensembles de données et d'évaluateurs](model-customize-open-weight-samples.md)

# Conditions préalables
<a name="model-customize-open-weight-prereq"></a>

Avant de commencer, effectuez les opérations obligatoires suivantes :
+ Intégrez un domaine SageMaker AI avec accès à Studio. Si vous n’êtes pas autorisé à définir Studio comme expérience par défaut pour votre domaine, contactez votre administrateur. Pour plus d'informations, consultez la [présentation du domaine Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-studio-onboard.html).
+ Mettez à jour le AWS CLI en suivant les étapes de [la section Installation de la AWS CLI version actuelle](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html#install-tool-bundled).
+ À partir de votre ordinateur local, exécutez `aws configure` et fournissez vos informations d’identification AWS . Pour plus d'informations sur les AWS informations d'identification, voir [Comprendre et obtenir vos AWS informations d'identification](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds.html).

## Autorisations IAM requises
<a name="model-customize-open-weight-iam"></a>

SageMaker La personnalisation du modèle d'IA nécessite l'ajout d'autorisations appropriées à l'exécution de votre domaine d' SageMaker IA. Pour ce faire, vous pouvez créer une politique d'autorisations IAM intégrée et l'associer au rôle IAM. Pour plus d'informations sur l'ajout de politiques, consultez la section [Ajout et suppression d'autorisations d'identité IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) dans le *guide de l'utilisateur AWS d'Identity and Access Management*.

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowNonAdminStudioActions",
            "Effect": "Allow",
            "Action": [
                "sagemaker:CreatePresignedDomainUrl",
                "sagemaker:DescribeDomain",
                "sagemaker:DescribeUserProfile",
                "sagemaker:DescribeSpace",
                "sagemaker:ListSpaces",
                "sagemaker:DescribeApp",
                "sagemaker:ListApps"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:*:domain/*",
                "arn:aws:sagemaker:*:*:user-profile/*",
                "arn:aws:sagemaker:*:*:app/*",
                "arn:aws:sagemaker:*:*:space/*"
             ]
        },
        {
            "Sid": "LambdaListPermissions",
            "Effect": "Allow",
            "Action": [
                "lambda:ListFunctions"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Sid": "LambdaPermissionsForRewardFunction",
            "Effect": "Allow",
            "Action": [
                "lambda:CreateFunction",
                "lambda:DeleteFunction",
                "lambda:InvokeFunction",
                "lambda:GetFunction"
            ],
            "Resource": [
                "arn:aws:lambda:*:*:function:*SageMaker*",
                "arn:aws:lambda:*:*:function:*sagemaker*",
                "arn:aws:lambda:*:*:function:*Sagemaker*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "LambdaLayerForAWSSDK",
            "Effect": "Allow",
            "Action": [
                "lambda:GetLayerVersion"
            ],
            "Resource": [
                "arn:aws:lambda:*:336392948345:layer:AWSSDK*"
            ]
        },
        {
            "Sid": "SageMakerPublicHubPermissions",
            "Effect": "Allow",
            "Action": [
                "sagemaker:ListHubContents"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:aws:hub/SageMakerPublicHub"
            ]
        },
        {
            "Sid": "SageMakerHubPermissions",
            "Effect": "Allow",
            "Action": [
                "sagemaker:ListHubs",
                "sagemaker:ListHubContents",
                "sagemaker:DescribeHubContent",
                "sagemaker:DeleteHubContent",
                "sagemaker:ListHubContentVersions",
                "sagemaker:Search"
            ],
            "Resource": [
                "*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "JumpStartAccess",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::jumpstart*"
            ]
        },
        {
            "Sid": "ListMLFlowOperations",
            "Effect": "Allow",
            "Action": [
                "sagemaker:ListMlflowApps",
                "sagemaker:ListMlflowTrackingServers"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Sid": "MLFlowAccess",
            "Effect": "Allow",
            "Action": [
                "sagemaker:UpdateMlflowApp",
                "sagemaker:DescribeMlflowApp",
                "sagemaker:CreatePresignedMlflowAppUrl",
                "sagemaker:CallMlflowAppApi",
                "sagemaker-mlflow:*"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:*:mlflow-app/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "BYODataSetS3Access",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::*SageMaker*",
                "arn:aws:s3:::*Sagemaker*",
                "arn:aws:s3:::*sagemaker*"
            ]
        },
        {
            "Sid": "AllowHubPermissions",
            "Effect": "Allow",
            "Action": [
                "sagemaker:ImportHubContent"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:*:hub/*",
                "arn:aws:sagemaker:*:*:hub-content/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "PassRoleForSageMaker",
            "Effect": "Allow",
            "Action": [
                "iam:PassRole"
            ],
            "Resource": [
                "arn:aws:iam::*:role/service-role/AmazonSageMaker-ExecutionRole-*"
            ],
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "sagemaker.amazonaws.com",
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "PassRoleForAWSLambda",
            "Effect": "Allow",
            "Action": [
                "iam:PassRole"
            ],
            "Resource": [
                "arn:aws:iam::*:role/service-role/AmazonSageMaker-ExecutionRole-*"
            ],
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "lambda.amazonaws.com",
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "PassRoleForBedrock",
            "Effect": "Allow",
            "Action": [
                "iam:PassRole"
            ],
            "Resource": [
                "arn:aws:iam::*:role/service-role/AmazonSageMaker-ExecutionRole-*"
            ],
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "bedrock.amazonaws.com",
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "TrainingJobRun",
            "Effect": "Allow",
            "Action": [
                "sagemaker:CreateTrainingJob",
                "sagemaker:DescribeTrainingJob",
                "sagemaker:ListTrainingJobs"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:*:training-job/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "ModelPackageAccess",
            "Effect": "Allow",
            "Action": [
                "sagemaker:CreateModelPackage",
                "sagemaker:DescribeModelPackage",
                "sagemaker:ListModelPackages",
                "sagemaker:CreateModelPackageGroup",
                "sagemaker:DescribeModelPackageGroup",
                "sagemaker:ListModelPackageGroups",
                "sagemaker:CreateModel"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:*:model-package-group/*",
                "arn:aws:sagemaker:*:*:model-package/*",
                "arn:aws:sagemaker:*:*:model/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "TagsPermission",
            "Effect": "Allow",
            "Action": [
                "sagemaker:AddTags",
                "sagemaker:ListTags"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:*:model-package-group/*",
                "arn:aws:sagemaker:*:*:model-package/*",
                "arn:aws:sagemaker:*:*:hub/*",
                "arn:aws:sagemaker:*:*:hub-content/*",
                "arn:aws:sagemaker:*:*:training-job/*",
                "arn:aws:sagemaker:*:*:model/*",
                "arn:aws:sagemaker:*:*:endpoint/*",
                "arn:aws:sagemaker:*:*:endpoint-config/*",
                "arn:aws:sagemaker:*:*:pipeline/*",
                "arn:aws:sagemaker:*:*:inference-component/*",
                "arn:aws:sagemaker:*:*:action/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "LogAccess",
            "Effect": "Allow",
            "Action": [
                "logs:DescribeLogGroups",
                "logs:DescribeLogStreams",
                "logs:GetLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:*:*:log-group*",
                "arn:aws:logs:*:*:log-group:/aws/sagemaker/TrainingJobs:log-stream:*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "BedrockDeploy",
            "Effect": "Allow",
            "Action": [
                "bedrock:CreateModelImportJob"
            ],
            "Resource": [
                "arn:aws:bedrock:*:*:*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "BedrockOperations",
            "Effect": "Allow",
            "Action": [
                "bedrock:GetModelImportJob",
                "bedrock:GetImportedModel",
                "bedrock:ListProvisionedModelThroughputs",
                "bedrock:ListCustomModelDeployments",
                "bedrock:ListCustomModels",
                "bedrock:ListModelImportJobs",
                "bedrock:GetEvaluationJob",
                "bedrock:CreateEvaluationJob", 
                "bedrock:InvokeModel"
            ],
            "Resource": [
                "arn:aws:bedrock:*:*:evaluation-job/*",
                "arn:aws:bedrock:*:*:imported-model/*",
                "arn:aws:bedrock:*:*:model-import-job/*",
                "arn:aws:bedrock:*:*:foundation-model/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "BedrockFoundationModelOperations",
            "Effect": "Allow",
            "Action": [
                "bedrock:GetFoundationModelAvailability",
                "bedrock:ListFoundationModels"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Sid": "SageMakerPipelinesAndLineage",
            "Effect": "Allow",
            "Action": [
                "sagemaker:ListActions",
                "sagemaker:ListArtifacts",
                "sagemaker:QueryLineage",
                "sagemaker:ListAssociations",
                "sagemaker:AddAssociation",
                "sagemaker:DescribeAction",
                "sagemaker:AddAssociation",
                "sagemaker:CreateAction",
                "sagemaker:CreateContext",
                "sagemaker:DescribeTrialComponent"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:*:artifact/*",
                "arn:aws:sagemaker:*:*:action/*",
                "arn:aws:sagemaker:*:*:context/*",
                "arn:aws:sagemaker:*:*:action/*",
                "arn:aws:sagemaker:*:*:model-package/*",
                "arn:aws:sagemaker:*:*:context/*",
                "arn:aws:sagemaker:*:*:pipeline/*",
                "arn:aws:sagemaker:*:*:experiment-trial-component/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "ListOperations",
            "Effect": "Allow",
            "Action": [
                "sagemaker:ListInferenceComponents",
                "sagemaker:ListWorkforces"
            ],
            "Resource": [
                "*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "SageMakerInference",
            "Effect": "Allow",
            "Action": [
                "sagemaker:DescribeInferenceComponent",
                "sagemaker:CreateEndpoint",
                "sagemaker:CreateEndpointConfig",
                "sagemaker:DescribeEndpoint",
                "sagemaker:DescribeEndpointConfig",
                "sagemaker:ListEndpoints"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:*:inference-component/*",
                "arn:aws:sagemaker:*:*:endpoint/*",
                "arn:aws:sagemaker:*:*:endpoint-config/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "SageMakerPipelines",
            "Effect": "Allow",
            "Action": [
                "sagemaker:DescribePipelineExecution",
                "sagemaker:ListPipelineExecutions",
                "sagemaker:ListPipelineExecutionSteps",
                "sagemaker:CreatePipeline",
                "sagemaker:UpdatePipeline",
                "sagemaker:StartPipelineExecution"
            ],
            "Resource": [
                "arn:aws:sagemaker:*:*:pipeline/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        }
    ]
}
```

Si vous l'avez attaché [AmazonSageMakerFullAccessPolicy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonSageMakerFullAccess.html)à votre rôle d'exécution, vous pouvez ajouter cette politique réduite :

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "LambdaListPermissions",
            "Effect": "Allow",
            "Action": [
                "lambda:ListFunctions"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Sid": "LambdaPermissionsForRewardFunction",
            "Effect": "Allow",
            "Action": [
                "lambda:CreateFunction",
                "lambda:DeleteFunction",
                "lambda:InvokeFunction",
                "lambda:GetFunction"
            ],
            "Resource": [
                "arn:aws:lambda:*:*:function:*SageMaker*",
                "arn:aws:lambda:*:*:function:*sagemaker*",
                "arn:aws:lambda:*:*:function:*Sagemaker*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "LambdaLayerForAWSSDK",
            "Effect": "Allow",
            "Action": [
                "lambda:GetLayerVersion"
            ],
            "Resource": [
                "arn:aws:lambda:*:336392948345:layer:AWSSDK*"
            ]
        },
        {
            "Sid": "S3Access",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::*SageMaker*",
                "arn:aws:s3:::*Sagemaker*",
                "arn:aws:s3:::*sagemaker*",
                "arn:aws:s3:::jumpstart*"
            ]
        },
        {
            "Sid": "PassRoleForSageMakerAndLambdaAndBedrock",
            "Effect": "Allow",
            "Action": [
                "iam:PassRole"
            ],
            "Resource": [
                "arn:aws:iam::*:role/service-role/AmazonSageMaker-ExecutionRole-*"
            ],
            "Condition": { 
                "StringEquals": { 
                    "iam:PassedToService": [ 
                        "lambda.amazonaws.com", 
                        "bedrock.amazonaws.com"
                     ],
                     "aws:ResourceAccount": "${aws:PrincipalAccount}" 
                 } 
            }
        },
        {
            "Sid": "BedrockDeploy",
            "Effect": "Allow",
            "Action": [
                "bedrock:CreateModelImportJob"
            ],
            "Resource": [
                "*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "BedrockOperations",
            "Effect": "Allow",
            "Action": [
                "bedrock:GetModelImportJob",
                "bedrock:GetImportedModel",
                "bedrock:ListProvisionedModelThroughputs",
                "bedrock:ListCustomModelDeployments",
                "bedrock:ListCustomModels",
                "bedrock:ListModelImportJobs",
                "bedrock:GetEvaluationJob",
                "bedrock:CreateEvaluationJob",
                "bedrock:InvokeModel"
            ],
            "Resource": [
                "arn:aws:bedrock:*:*:evaluation-job/*",
                "arn:aws:bedrock:*:*:imported-model/*",
                "arn:aws:bedrock:*:*:model-import-job/*",
                "arn:aws:bedrock:*:*:foundation-model/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "${aws:PrincipalAccount}"
                }
            }
        },
        {
            "Sid": "BedrockFoundationModelOperations",
            "Effect": "Allow",
            "Action": [
                "bedrock:GetFoundationModelAvailability",
                "bedrock:ListFoundationModels"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

Vous devez ensuite cliquer sur **Modifier la politique de confiance** et la remplacer par la politique suivante, puis cliquer sur **Mettre à jour la politique**.

```
{
    "Version": "2012-10-17",		 	 	                    
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                 "Service": "lambda.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        },
        {
            "Effect": "Allow",
            "Principal": {
                   "Service": "sagemaker.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        },
        {
            "Effect": "Allow",
            "Principal": {
                  "Service": "bedrock.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```

# Création de ressources pour la personnalisation des modèles dans l'interface utilisateur
<a name="model-customize-open-weight-create-assets-ui"></a>

Vous pouvez créer et gérer les actifs du jeu de données et de l'évaluateur que vous pouvez utiliser pour personnaliser le modèle dans l'interface utilisateur.

## Assets
<a name="model-customize-open-weight-assets"></a>

Sélectionnez **Assets** dans le panneau de gauche et dans l'interface utilisateur d'Amazon SageMaker Studio, puis sélectionnez **Datasets.**

![\[Une image contenant l'accès à la personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-16.png)


Choisissez **Upload Dataset** pour ajouter le jeu de données que vous utiliserez dans vos tâches de personnalisation de modèles. En choisissant le **format de saisie de données requis**, vous pouvez accéder à une référence du format de jeu de données à utiliser.

![\[Une image contenant l'accès à la personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-15.png)


## Évaluateurs
<a name="model-customize-open-weight-evaluators"></a>

Vous pouvez également ajouter des **fonctions de récompense** et des **invites de récompense** pour vos tâches de personnalisation de l'apprentissage par renforcement.

![\[Une image contenant l'accès à la personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-14.png)


L'interface utilisateur fournit également des conseils sur le format requis pour la fonction de récompense ou l'invite de récompense.

![\[Une image contenant l'accès à la personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-13.png)


## Ressources pour la personnalisation des modèles à l'aide du AWS SDK
<a name="model-customize-open-weight-create-assets-sdk"></a>

Vous pouvez également utiliser le SDK SageMaker AI Python pour créer des actifs. Voir un exemple d'extrait de code ci-dessous :

```
from sagemaker.ai_registry.air_constants import REWARD_FUNCTION, REWARD_PROMPT
from sagemaker.ai_registry.dataset import DataSet, CustomizationTechnique
from sagemaker.ai_registry.evaluator import Evaluator

# Creating a dataset example
dataset = DataSet.create(
            name="sdkv3-gen-ds2",
            source="s3://sample-test-bucket/datasets/training-data/jamjee-sft-ds1.jsonl", # or use local filepath as source.
            customization_technique=CustomizationTechnique.SFT
        )

# Refreshes status from hub
dataset.refresh()
pprint(dataset.__dict__)

# Creating an evaluator. Method : Lambda
evaluator = Evaluator.create(
                name = "sdk-new-rf11",
                source="arn:aws:lambda:us-west-2:<>:function:<function-name>8",
                type=REWARD_FUNCTION
        )

# Creating an evaluator. Method : Bring your own code
evaluator = Evaluator.create(
                name = "eval-lambda-test",
                source="/path_to_local/eval_lambda_1.py",
                type = REWARD_FUNCTION
        )

# Optional wait, by default we have wait = True during create call.
evaluator.wait()

evaluator.refresh()
pprint(evaluator)
```

# Soumission de tâches de personnalisation de modèles d'IA
<a name="model-customize-open-weight-job"></a>

La fonctionnalité de personnalisation des modèles d' SageMaker IA est accessible depuis la page Modèles d'Amazon SageMaker Studio dans le panneau de gauche. Vous pouvez également trouver la page Ressources où vous pouvez créer et gérer les ensembles de données et les évaluateurs de personnalisation de votre modèle.

![\[Une image contenant l'accès à la personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-12.png)


Pour commencer à soumettre une tâche de personnalisation de modèle, sélectionnez l'option Modèles pour accéder à l'onglet Jumpstart Base Models :

![\[Une image expliquant comment choisir le modèle de base.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-11.png)


Vous pouvez directement cliquer sur Personnaliser le modèle dans la fiche modèle ou rechercher n'importe quel modèle de Meta que vous souhaitez personnaliser.

![\[Une image contenant la carte modèle et expliquant comment choisir le modèle à personnaliser.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-10.png)


Après avoir cliqué sur la fiche modèle, vous pouvez accéder à la page des détails du modèle et lancer la tâche de personnalisation en cliquant sur Personnaliser le modèle, puis en sélectionnant Personnaliser avec l'interface utilisateur pour démarrer la configuration de votre tâche RLVR.

![\[Une image expliquant comment lancer la tâche de personnalisation.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-9.png)


Vous pouvez ensuite saisir le nom de votre modèle personnalisé, sélectionner la technique de personnalisation du modèle à utiliser et configurer les hyperparamètres de votre tâche :

![\[Une image contenant une sélection de techniques de personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-8.png)


![\[Une image contenant une sélection de techniques de personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-7.png)


## Soumission de tâches de personnalisation de modèles d'IA à l'aide du SDK
<a name="model-customize-open-weight-job-sdk"></a>

Vous pouvez également utiliser le SDK SageMaker AI Python pour soumettre une tâche de personnalisation du modèle :

```
# Submit a DPO model customization job

from sagemaker.modules.train.dpo_trainer import DPOTrainer
from sagemaker.modules.train.common import TrainingType

trainer = DPOTrainer(
    model=BASE_MODEL,
    training_type=TrainingType.LORA,
    model_package_group_name=MODEL_PACKAGE_GROUP_NAME,
    training_dataset=TRAINING_DATASET,
    s3_output_path=S3_OUTPUT_PATH,
    sagemaker_session=sagemaker_session,
    role=ROLE_ARN
)
```

## Surveillance de votre tâche de personnalisation
<a name="model-customize-open-weight-monitor"></a>

Immédiatement après avoir soumis votre offre d'emploi, vous serez redirigé vers la page de formation à la personnalisation de votre modèle.

![\[Une image contenant une sélection de techniques de personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-6.png)


Une fois le travail terminé, vous pouvez accéder à la page de détails de votre modèle personnalisé en cliquant sur le bouton Accéder au **modèle personnalisé** dans le coin supérieur droit.

![\[Une image contenant une sélection de techniques de personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-5.png)


Sur la page des détails du modèle personnalisé, vous pouvez continuer à travailler avec votre modèle personnalisé en :

1. Vérification des informations relatives aux performances, à l'emplacement des artefacts générés, aux hyperparamètres de configuration de l'entraînement et aux journaux d'entraînement.

1. Lancez une tâche d'évaluation avec un autre ensemble de données (personnalisation continue).

1. Déployez le modèle à l'aide des points de terminaison SageMaker AI Inference ou d'Amazon Bedrock Custom Model Import.  
![\[Une image contenant une sélection de techniques de personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-4.png)

# Soumission d'une tâche d'évaluation du modèle
<a name="model-customize-open-weight-evaluation"></a>

Cette section décrit l'évaluation de modèles personnalisés à poids ouvert. Il vous permet de commencer par une présentation détaillée du processus de soumission des tâches d'évaluation. Des ressources supplémentaires sont fournies pour des cas d'utilisation plus avancés de soumission de tâches d'évaluation.

**Topics**
+ [Démarrage](model-customize-evaluation-getting-started.md)
+ [Types d'évaluation et soumission de Job](model-customize-evaluation-types.md)
+ [Formats de métriques d'évaluation](model-customize-evaluation-metrics-formats.md)
+ [Formats de jeu de données pris en charge pour les tâches Bring-Your-Own-Dataset (BYOD)](model-customize-evaluation-dataset-formats.md)
+ [Évaluez à l'aide de marqueurs prédéfinis et personnalisés](model-customize-evaluation-preset-custom-scorers.md)

# Démarrage
<a name="model-customize-evaluation-getting-started"></a>

## Soumettre un travail d'évaluation via SageMaker Studio
<a name="model-customize-evaluation-studio"></a>

### Étape 1 : Accédez à l'évaluation à partir de votre carte modèle
<a name="model-customize-evaluation-studio-step1"></a>

Après avoir personnalisé votre modèle, accédez à la page d'évaluation depuis votre fiche modèle.

Pour plus d'informations sur l'entraînement sur modèle personnalisé avec poids libre : [https://docs.aws.amazon.com/sagemaker/latest/dg/model- .html customize-open-weight-job](https://docs.aws.amazon.com/sagemaker/latest/dg/model-customize-open-weight-job.html)

SageMaker visualise votre modèle personnalisé dans l'onglet Mes modèles :

![\[Page de carte modèle enregistrée\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/getting-started-registered-model-card.png)


Choisissez Afficher la dernière version, puis sélectionnez Évaluer :

![\[Page de personnalisation du modèle\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/getting-started-evaluate-from-model-card.png)


### Étape 2 : Soumettez votre job d'évaluation
<a name="model-customize-evaluation-studio-step2"></a>

Cliquez sur le bouton Soumettre et soumettez votre travail d'évaluation. Cela soumet une tâche de référence minimale au MMLU.

Pour plus d'informations sur les types de tâches d'évaluation pris en charge, consultez[Types d'évaluation et soumission de Job](model-customize-evaluation-types.md).

![\[Page de soumission des tâches d'évaluation\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/getting-started-benchmark-submission.png)


### Étape 3 : Suivez la progression de votre job d'évaluation
<a name="model-customize-evaluation-studio-step3"></a>

La progression de votre tâche d'évaluation est suivie dans l'onglet Étapes d'évaluation :

![\[L'avancement de votre tâche d'évaluation\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/getting-started-benchmark-tracking.png)


### Étape 4 : Afficher les résultats de votre job d'évaluation
<a name="model-customize-evaluation-studio-step4"></a>

Les résultats de votre travail d'évaluation sont visualisés dans l'onglet Résultats de l'évaluation :

![\[Les indicateurs de votre travail d'évaluation\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/getting-started-benchmark-results.png)


### Étape 5 : Afficher vos évaluations terminées
<a name="model-customize-evaluation-studio-step5"></a>

Votre tâche d'évaluation terminée est affichée dans Évaluations de votre modèle de carte :

![\[Vos tâches d'évaluation terminées\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/getting-started-benchmark-completed-model-card.png)


## Soumettez votre travail d'évaluation via le SDK SageMaker Python
<a name="model-customize-evaluation-sdk"></a>

### Étape 1 : Créez votre BenchMarkEvaluator
<a name="model-customize-evaluation-sdk-step1"></a>

Transmettez votre modèle entraîné enregistré, l'emplacement de sortie AWS S3 et l'ARN MLFlow des ressources à, `BenchMarkEvaluator` puis initialisez-les.

```
from sagemaker.train.evaluate import BenchMarkEvaluator, Benchmark  
  
evaluator = BenchMarkEvaluator(  
    benchmark=Benchmark.MMLU,  
    model="arn:aws:sagemaker:<region>:<account-id>:model-package/<model-package-name>/<version>",  
    s3_output_path="s3://<bucket-name>/<prefix>/eval/",  
    mlflow_resource_arn="arn:aws:sagemaker:<region>:<account-id>:mlflow-tracking-server/<tracking-server-name>",  
    evaluate_base_model=False  
)
```

### Étape 2 : Soumettez votre job d'évaluation
<a name="model-customize-evaluation-sdk-step2"></a>

Appelez la `evaluate()` méthode pour soumettre le travail d'évaluation.

```
execution = evaluator.evaluate()
```

### Étape 3 : Suivez la progression de votre job d'évaluation
<a name="model-customize-evaluation-sdk-step3"></a>

Appelez la `wait()` méthode d'exécution pour obtenir une mise à jour en temps réel de l'avancement de la tâche d'évaluation.

```
execution.wait(target_status="Succeeded", poll=5, timeout=3600)
```

### Étape 4 : Afficher les résultats de votre job d'évaluation
<a name="model-customize-evaluation-sdk-step4"></a>

Appelez la `show_results()` méthode pour afficher les résultats de votre tâche d'évaluation.

```
execution.show_results()
```

# Types d'évaluation et soumission de Job
<a name="model-customize-evaluation-types"></a>

## Analyse comparative avec des ensembles de données standardisés
<a name="model-customize-evaluation-benchmarking"></a>

Utilisez le type d'évaluation de référence pour évaluer la qualité de votre modèle dans des ensembles de données de référence standardisés, y compris des ensembles de données populaires tels que MMLU et BBH.


| Comparaison | Ensemble de données personnalisé pris en charge | Modalités | Description | Métriques | Stratégie | Sous-tâche disponible | 
| --- | --- | --- | --- | --- | --- | --- | 
| mmlu | Non | Texte | Compréhension linguistique multitâche : teste les connaissances dans 57 domaines. | précision | zs\$1cot | Oui | 
| mmlu\$1pro | Non | Texte | MMLU – Sous-ensemble professionnel : se concentre sur les domaines professionnels tels que le droit, la médecine, la comptabilité et l’ingénierie. | précision | zs\$1cot | Non | 
| bbh | Non | Texte | Tâches de raisonnement avancées : ensemble de problèmes difficiles qui mettent à l’épreuve des compétences cognitives et de résolution de problèmes de haut niveau. | précision | fs\$1cot | Oui | 
| gpqa | Non | Texte | Réponses aux questions de physique générale : évalue la compréhension des concepts de physique et les capacités de résolution de problèmes connexes. | précision | zs\$1cot | Non | 
| math | Non | Texte | Résolution de problèmes mathématiques : mesure le raisonnement mathématique dans des domaines tels que l’algèbre, le calcul et les problèmes de mots. | exact\$1match | zs\$1cot | Oui | 
| strong\$1reject | Non | Texte | Tâche de contrôle qualité : teste la capacité du modèle à détecter et à rejeter le contenu inapproprié, préjudiciable ou incorrect. | deflection | zs | Oui | 
| ifeval | Non | Texte | Évaluation suivant les instructions : évalue la précision avec laquelle un modèle suit les instructions données et exécute les tâches conformément aux spécifications. | précision | zs | Non | 

Pour plus d'informations sur les formats BYOD, consultez[Formats de jeu de données pris en charge pour les tâches Bring-Your-Own-Dataset (BYOD)](model-customize-evaluation-dataset-formats.md).

### Sous-tâches disponibles
<a name="model-customize-evaluation-benchmarking-subtasks"></a>

La liste suivante répertorie les sous-tâches disponibles pour l'évaluation de modèles dans plusieurs domaines, notamment MMLU (Massive Multitask Language Understanding), BBH (Big Bench Hard) et MATH. StrongReject Ces sous-tâches vous permettent d’évaluer les performances de votre modèle par rapport à des capacités et à des domaines de connaissances spécifiques.

**Sous-tâches du MMLU**

```
MMLU_SUBTASKS = [
    "abstract_algebra",
    "anatomy",
    "astronomy",
    "business_ethics",
    "clinical_knowledge",
    "college_biology",
    "college_chemistry",
    "college_computer_science",
    "college_mathematics",
    "college_medicine",
    "college_physics",
    "computer_security",
    "conceptual_physics",
    "econometrics",
    "electrical_engineering",
    "elementary_mathematics",
    "formal_logic",
    "global_facts",
    "high_school_biology",
    "high_school_chemistry",
    "high_school_computer_science",
    "high_school_european_history",
    "high_school_geography",
    "high_school_government_and_politics",
    "high_school_macroeconomics",
    "high_school_mathematics",
    "high_school_microeconomics",
    "high_school_physics",
    "high_school_psychology",
    "high_school_statistics",
    "high_school_us_history",
    "high_school_world_history",
    "human_aging",
    "human_sexuality",
    "international_law",
    "jurisprudence",
    "logical_fallacies",
    "machine_learning",
    "management",
    "marketing",
    "medical_genetics",
    "miscellaneous",
    "moral_disputes",
    "moral_scenarios",
    "nutrition",
    "philosophy",
    "prehistory",
    "professional_accounting",
    "professional_law",
    "professional_medicine",
    "professional_psychology",
    "public_relations",
    "security_studies",
    "sociology",
    "us_foreign_policy",
    "virology",
    "world_religions"
]
```

**Sous-tâches BBH**

```
BBH_SUBTASKS = [
    "boolean_expressions",
    "causal_judgement",
    "date_understanding",
    "disambiguation_qa",
    "dyck_languages",
    "formal_fallacies",
    "geometric_shapes",
    "hyperbaton",
    "logical_deduction_five_objects",
    "logical_deduction_seven_objects",
    "logical_deduction_three_objects",
    "movie_recommendation",
    "multistep_arithmetic_two",
    "navigate",
    "object_counting",
    "penguins_in_a_table",
    "reasoning_about_colored_objects",
    "ruin_names",
    "salient_translation_error_detection",
    "snarks",
    "sports_understanding",
    "temporal_sequences",
    "tracking_shuffled_objects_five_objects",
    "tracking_shuffled_objects_seven_objects",
    "tracking_shuffled_objects_three_objects",
    "web_of_lies",
    "word_sorting"
]
```

**Sous-tâches mathématiques**

```
MATH_SUBTASKS = [
    "algebra", 
    "counting_and_probability", 
    "geometry",
    "intermediate_algebra", 
    "number_theory", 
    "prealgebra", 
    "precalculus"
]
```

**StrongReject Sous-tâches**

```
STRONG_REJECT_SUBTASKS = [
    "gcg_transfer_harmbench", 
    "gcg_transfer_universal_attacks",
    "combination_3", 
    "combination_2", 
    "few_shot_json", 
    "dev_mode_v2",
    "dev_mode_with_rant",
    "wikipedia_with_title", 
    "distractors",
    "wikipedia",
     "style_injection_json", 
    "style_injection_short",
    "refusal_suppression", 
    "prefix_injection", 
    "distractors_negated",
    "poems", 
    "base64", 
    "base64_raw", "
    base64_input_only",
    "base64_output_only", 
    "evil_confidant", 
    "aim", 
    "rot_13",
    "disemvowel", 
    "auto_obfuscation", 
    "auto_payload_splitting", 
    "pair",
    "pap_authority_endorsement", 
    "pap_evidence_based_persuasion",
    "pap_expert_endorsement", 
    "pap_logical_appeal", 
    "pap_misrepresentation"
]
```

### Soumettez votre offre d'emploi de référence
<a name="model-customize-evaluation-benchmarking-submit"></a>

------
#### [ SageMaker Studio ]

![\[Une configuration minimale pour l'analyse comparative via Studio SageMaker\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/benchmark-submission-sagemaker-studio.png)


------
#### [ SageMaker Python SDK ]

```
from sagemaker.train.evaluate import get_benchmarks
from sagemaker.train.evaluate import BenchMarkEvaluator

Benchmark = get_benchmarks()

# Create evaluator with MMLU benchmark
evaluator = BenchMarkEvaluator(
benchmark=Benchmark.MMLU,
model="arn:aws:sagemaker:<region>:<account-id>:model-package/<model-package-name>/<version>",
s3_output_path="s3://<bucket-name>/<prefix>/",
evaluate_base_model=False
)

execution = evaluator.evaluate()
```

Pour plus d'informations sur la soumission de tâches d'évaluation via le SDK SageMaker Python, voir : [https://sagemaker.readthedocs.io/en/stable/model\$1customization/evaluation.html](https://sagemaker.readthedocs.io/en/stable/model_customization/evaluation.html)

------

## Évaluation du modèle linguistique étendu en tant que juge (LLMAJ)
<a name="model-customize-evaluation-llmaj"></a>

Utilisez l'évaluation LLM-as-a-judge (LLMAJ) pour tirer parti d'un autre modèle de pointe afin de classer les réponses de votre modèle cible. Vous pouvez utiliser les modèles AWS Bedrock comme juges en appelant `create_evaluation_job` l'API pour lancer la tâche d'évaluation.

Pour plus d'informations sur les modèles de juges pris en charge, voir : [https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html)

Vous pouvez utiliser deux formats de mesures différents pour définir l'évaluation :
+ **Métriques intégrées : Tirez parti des métriques** intégrées de AWS Bedrock pour analyser la qualité des réponses d'inférence de votre modèle. Pour plus d'informations, voir : [https://docs.aws.amazon.com/bedrock/latest/userguide/model- evaluation-type-judge-prompt .html](https://docs.aws.amazon.com/bedrock/latest/userguide/model-evaluation-type-judge-prompt.html)
+ **Métriques personnalisées :** définissez vos propres métriques personnalisées dans le format de métrique personnalisé de Bedrock Evaluation pour analyser la qualité des réponses d'inférence de votre modèle à l'aide de vos propres instructions. Pour plus d'informations, voir : [https://docs.aws.amazon.com/bedrock/latest/userguide/model- evaluation-custom-metrics-prompt -formats.html](https://docs.aws.amazon.com/bedrock/latest/userguide/model-evaluation-custom-metrics-prompt-formats.html)

### Soumettre une tâche LLMAJ de métriques intégrée
<a name="model-customize-evaluation-llmaj-builtin"></a>

------
#### [ SageMaker Studio ]

![\[Une configuration minimale pour le benchmarking LLMAJ via Studio SageMaker\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/llmaj-as-judge-submission-sagemaker-studio.png)


------
#### [ SageMaker Python SDK ]

```
from sagemaker.train.evaluate import LLMAsJudgeEvaluator

evaluator = LLMAsJudgeEvaluator(
    model="arn:aws:sagemaker:<region>:<account-id>:model-package/<model-package-name>/<version>",
    evaluator_model="<bedrock-judge-model-id>",
    dataset="s3://<bucket-name>/<prefix>/<dataset-file>.jsonl",
    builtin_metrics=["<builtin-metric-1>", "<builtin-metric-2>"],
    s3_output_path="s3://<bucket-name>/<prefix>/",
    evaluate_base_model=False
)

execution = evaluator.evaluate()
```

Pour plus d'informations sur la soumission de tâches d'évaluation via le SDK SageMaker Python, voir : [https://sagemaker.readthedocs.io/en/stable/model\$1customization/evaluation.html](https://sagemaker.readthedocs.io/en/stable/model_customization/evaluation.html)

------

### Soumettre une tâche LLMAJ de métriques personnalisée
<a name="model-customize-evaluation-llmaj-custom"></a>

Définissez vos métriques personnalisées :

```
{
    "customMetricDefinition": {
        "name": "PositiveSentiment",
        "instructions": (
            "You are an expert evaluator. Your task is to assess if the sentiment of the response is positive. "
            "Rate the response based on whether it conveys positive sentiment, helpfulness, and constructive tone.\n\n"
            "Consider the following:\n"
            "- Does the response have a positive, encouraging tone?\n"
            "- Is the response helpful and constructive?\n"
            "- Does it avoid negative language or criticism?\n\n"
            "Rate on this scale:\n"
            "- Good: Response has positive sentiment\n"
            "- Poor: Response lacks positive sentiment\n\n"
            "Here is the actual task:\n"
            "Prompt: {{prompt}}\n"
            "Response: {{prediction}}"
        ),
        "ratingScale": [
            {"definition": "Good", "value": {"floatValue": 1}},
            {"definition": "Poor", "value": {"floatValue": 0}}
        ]
    }
}
```

Pour plus d'informations, voir : [https://docs.aws.amazon.com/bedrock/latest/userguide/model- evaluation-custom-metrics-prompt -formats.html](https://docs.aws.amazon.com/bedrock/latest/userguide/model-evaluation-custom-metrics-prompt-formats.html)

------
#### [ SageMaker Studio ]

![\[Téléchargez la métrique personnalisée via Métriques personnalisées > Ajouter des métriques personnalisées\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/custom-llmaj-metrics-submission-sagemaker-studio.png)


------
#### [ SageMaker Python SDK ]

```
evaluator = LLMAsJudgeEvaluator(
    model="arn:aws:sagemaker:<region>:<account-id>:model-package/<model-package-name>/<version>",
    evaluator_model="<bedrock-judge-model-id>",
    dataset="s3://<bucket-name>/<prefix>/<dataset-file>.jsonl",
    custom_metrics=custom_metric_dict = {
        "customMetricDefinition": {
            "name": "PositiveSentiment",
            "instructions": (
                "You are an expert evaluator. Your task is to assess if the sentiment of the response is positive. "
                "Rate the response based on whether it conveys positive sentiment, helpfulness, and constructive tone.\n\n"
                "Consider the following:\n"
                "- Does the response have a positive, encouraging tone?\n"
                "- Is the response helpful and constructive?\n"
                "- Does it avoid negative language or criticism?\n\n"
                "Rate on this scale:\n"
                "- Good: Response has positive sentiment\n"
                "- Poor: Response lacks positive sentiment\n\n"
                "Here is the actual task:\n"
                "Prompt: {{prompt}}\n"
                "Response: {{prediction}}"
            ),
            "ratingScale": [
                {"definition": "Good", "value": {"floatValue": 1}},
                {"definition": "Poor", "value": {"floatValue": 0}}
            ]
        }
    },
    s3_output_path="s3://<bucket-name>/<prefix>/",
    evaluate_base_model=False
)
```

------

## Scorers personnalisés
<a name="model-customize-evaluation-custom-scorers"></a>

Définissez votre propre fonction de notation personnalisée pour lancer une tâche d'évaluation. Le système fournit deux marqueurs intégrés : Prime math et Prime code. Vous pouvez également apporter votre propre fonction de score. Vous pouvez copier directement le code de votre fonction scorer ou apporter votre propre définition de fonction Lambda à l'aide de l'ARN associé. Par défaut, les deux types de marqueurs produisent des résultats d'évaluation qui incluent des métriques standard telles que le score F1, ROUGE et BLEU.

Pour plus d'informations sur les évaluateurs intégrés et personnalisés et leurs exigences/contrats respectifs, voir. [Évaluez à l'aide de marqueurs prédéfinis et personnalisés](model-customize-evaluation-preset-custom-scorers.md)

### Enregistrez votre jeu de données
<a name="model-customize-evaluation-custom-scorers-register-dataset"></a>

Apportez votre propre jeu de données pour un scorer personnalisé en l'enregistrant en tant que jeu de données SageMaker Hub Content Dataset.

------
#### [ SageMaker Studio ]

Dans Studio, chargez votre jeu de données à l'aide de la page dédiée aux ensembles de données.

![\[Ensemble de données d'évaluation enregistré dans SageMaker Studio\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/dataset-registration-sagemaker-studio.png)


------
#### [ SageMaker Python SDK ]

Dans le SDK SageMaker Python, téléchargez votre ensemble de données à l'aide de la page dédiée aux ensembles de données.

```
from sagemaker.ai_registry.dataset import DataSet

dataset = DataSet.create(
    name="your-bring-your-own-dataset",
    source="s3://<bucket-name>/<prefix>/<dataset-file>.jsonl"
)
dataset.refresh()
```

------

### Soumettre une tâche de scorer intégrée
<a name="model-customize-evaluation-custom-scorers-builtin"></a>

------
#### [ SageMaker Studio ]

![\[Choisissez parmi des exécutions de code ou des réponses mathématiques pour une notation personnalisée intégrée\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/builtin-scorer-submission-sagemaker-studio.png)


------
#### [ SageMaker Python SDK ]

```
from sagemaker.train.evaluate import CustomScorerEvaluator
from sagemaker.train.evaluate import get_builtin_metrics

BuiltInMetric = get_builtin_metrics()

evaluator_builtin = CustomScorerEvaluator(
    evaluator=BuiltInMetric.PRIME_MATH,
    dataset="arn:aws:sagemaker:<region>:<account-id>:hub-content/<hub-content-id>/DataSet/your-bring-your-own-dataset/<version>",
    model="arn:aws:sagemaker:<region>:<account-id>:model-package/<model-package-name>/<version>",
    s3_output_path="s3://<bucket-name>/<prefix>/",
    evaluate_base_model=False
)

execution = evaluator.evaluate()
```

Sélectionnez parmi `BuiltInMetric.PRIME_MATH` ou `BuiltInMetric.PRIME_CODE` pour la notation intégrée.

------

### Soumettre un job de scorer personnalisé
<a name="model-customize-evaluation-custom-scorers-custom"></a>

Définissez une fonction de récompense personnalisée. Pour de plus amples informations, veuillez consulter [Scorateurs personnalisés (apportez vos propres statistiques)](model-customize-evaluation-preset-custom-scorers.md#model-customize-evaluation-custom-scorers-byom).

**Enregistrez la fonction de récompense personnalisée**

------
#### [ SageMaker Studio ]

![\[Accédez à SageMaker Studio > Ressources > Évaluateur > Créer un évaluateur > Créer une fonction de récompense\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/custom-scorer-submission-sagemaker-studio.png)


![\[Soumettez la tâche d'évaluation de Custom Scorer faisant référence à la fonction de récompense prédéfinie enregistrée dans Custom Scorer > Métriques personnalisées\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/custom-scorer-benchmark-submission-sagemaker-studio.png)


------
#### [ SageMaker Python SDK ]

```
from sagemaker.ai_registry.evaluator import Evaluator
from sagemaker.ai_registry.air_constants import REWARD_FUNCTION

evaluator = Evaluator.create(
    name = "your-reward-function-name",
    source="/path_to_local/custom_lambda_function.py",
    type = REWARD_FUNCTION
)
```

```
evaluator = CustomScorerEvaluator(
    evaluator=evaluator,
    dataset="s3://<bucket-name>/<prefix>/<dataset-file>.jsonl",
    model="arn:aws:sagemaker:<region>:<account-id>:model-package/<model-package-name>/<version>",
    s3_output_path="s3://<bucket-name>/<prefix>/",
    evaluate_base_model=False
)

execution = evaluator.evaluate()
```

------

# Formats de métriques d'évaluation
<a name="model-customize-evaluation-metrics-formats"></a>

Évaluation de la qualité de votre modèle dans les formats de mesure suivants :
+ Résumé de l'évaluation du modèle
+ MLFlow
+ TensorBoard

## Résumé de l'évaluation du modèle
<a name="model-customize-evaluation-metrics-summary"></a>

Lorsque vous soumettez votre travail d'évaluation, vous spécifiez un emplacement de sortie AWS S3. SageMaker télécharge automatiquement le fichier .json du résumé de l'évaluation à l'emplacement. Le chemin S3 du résumé du benchmark est le suivant :

```
s3://<your-provide-s3-location>/<training-job-name>/output/output/<evaluation-job-name>/eval_results/
```

**Passez la position AWS S3**

------
#### [ SageMaker Studio ]

![\[Passer à l'emplacement de l'artefact de sortie (URI AWS S3)\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/s3-output-path-submission-sagemaker-studio.png)


------
#### [ SageMaker Python SDK ]

```
evaluator = BenchMarkEvaluator(
    benchmark=Benchmark.MMLU,
    model="arn:aws:sagemaker:<region>:<account-id>:model-package/<model-package-name>/<version>",
    s3_output_path="s3://<bucket-name>/<prefix>/eval/",
    evaluate_base_model=False
)

execution = evaluator.evaluate()
```

------

Lisez-le directement `.json` depuis l'emplacement AWS S3 ou visualisez-le automatiquement dans l'interface utilisateur :

```
{
  "results": {
    "custom|gen_qa_gen_qa|0": {
      "rouge1": 0.9152812653966208,
      "rouge1_stderr": 0.003536439199232507,
      "rouge2": 0.774569918517409,
      "rouge2_stderr": 0.006368825746765958,
      "rougeL": 0.9111255645823356,
      "rougeL_stderr": 0.003603841524881021,
      "em": 0.6562150055991042,
      "em_stderr": 0.007948251702846893,
      "qem": 0.7522396416573348,
      "qem_stderr": 0.007224355240883467,
      "f1": 0.8428757602152095,
      "f1_stderr": 0.005186300690881584,
      "f1_score_quasi": 0.9156170336744968,
      "f1_score_quasi_stderr": 0.003667700152375464,
      "bleu": 100.00000000000004,
      "bleu_stderr": 1.464411857851008
    },
    "all": {
      "rouge1": 0.9152812653966208,
      "rouge1_stderr": 0.003536439199232507,
      "rouge2": 0.774569918517409,
      "rouge2_stderr": 0.006368825746765958,
      "rougeL": 0.9111255645823356,
      "rougeL_stderr": 0.003603841524881021,
      "em": 0.6562150055991042,
      "em_stderr": 0.007948251702846893,
      "qem": 0.7522396416573348,
      "qem_stderr": 0.007224355240883467,
      "f1": 0.8428757602152095,
      "f1_stderr": 0.005186300690881584,
      "f1_score_quasi": 0.9156170336744968,
      "f1_score_quasi_stderr": 0.003667700152375464,
      "bleu": 100.00000000000004,
      "bleu_stderr": 1.464411857851008
    }
  }
}
```

![\[Exemples de mesures de performance pour le benchmark gen-qa personnalisé visualisé dans Studio SageMaker\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/gen-qa-metrics-visualization-sagemaker-studio.png)


## MLFlow journalisation
<a name="model-customize-evaluation-metrics-mlflow"></a>

**Fournissez l'ARN SageMaker MLFlow de votre ressource**

SageMaker Studio utilise l' MLFlow application par défaut qui est mise en service sur chaque domaine Studio lorsque vous utilisez la fonctionnalité de personnalisation du modèle pour la première fois. SageMaker Studio utilise l'ARN associé par défaut à MLflow l'application lors de la soumission des tâches d'évaluation.

Vous pouvez également soumettre votre travail d'évaluation et fournir explicitement un ARN de MLFlow ressource pour transmettre les métriques au suivi associé à des server/app fins d'analyse en temps réel.

**SageMaker SDK Python**

```
evaluator = BenchMarkEvaluator(
    benchmark=Benchmark.MMLU,
    model="arn:aws:sagemaker:<region>:<account-id>:model-package/<model-package-name>/<version>",
    s3_output_path="s3://<bucket-name>/<prefix>/eval/",
    mlflow_resource_arn="arn:aws:sagemaker:<region>:<account-id>:mlflow-tracking-server/<tracking-server-name>",
    evaluate_base_model=False
)

execution = evaluator.evaluate()
```

Visualisation des métriques au niveau du modèle et au niveau du système :

![\[Exemple d'erreur et de précision au niveau du modèle pour la tâche d'analyse comparative MMLU\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/model-metrics-mlflow.png)


![\[Exemples de métriques intégrées pour la tâche d'analyse comparative LLMAJ\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/llmaj-metrics-mlflow.png)


![\[Exemples de mesures au niveau du système pour la tâche d'analyse comparative de la MMLU\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/system-metrics-mlflow.png)


## TensorBoard
<a name="model-customize-evaluation-metrics-tensorboard"></a>

Soumettez votre travail d'évaluation avec un emplacement de sortie AWS S3. SageMaker télécharge automatiquement un TensorBoard fichier à l'emplacement.

SageMaker télécharge le TensorBoard fichier sur AWS S3 à l'emplacement suivant :

```
s3://<your-provide-s3-location>/<training-job-name>/output/output/<evaluation-job-name>/tensorboard_results/eval/
```

**Transmettez l'emplacement AWS S3 comme suit**

------
#### [ SageMaker Studio ]

![\[Passer à l'emplacement de l'artefact de sortie (URI AWS S3)\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/s3-output-path-submission-sagemaker-studio.png)


------
#### [ SageMaker Python SDK ]

```
evaluator = BenchMarkEvaluator(
    benchmark=Benchmark.MMLU,
    model="arn:aws:sagemaker:<region>:<account-id>:model-package/<model-package-name>/<version>",
    s3_output_path="s3://<bucket-name>/<prefix>/eval/",
    evaluate_base_model=False
)

execution = evaluator.evaluate()
```

------

**Exemples de mesures au niveau du modèle**

![\[SageMaker TensorBoard affichage des résultats d'une tâche d'analyse comparative\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/metrics-in-tensorboard.png)


# Formats de jeu de données pris en charge pour les tâches Bring-Your-Own-Dataset (BYOD)
<a name="model-customize-evaluation-dataset-formats"></a>

Le score personnalisé et les types LLM-as-judge d'évaluation nécessitent un fichier JSONL de jeu de données personnalisé situé dans S3. AWS Vous devez fournir le fichier sous la forme d'un fichier de lignes JSON respectant l'un des formats pris en charge suivants. Les exemples de ce document sont développés pour plus de clarté.

Chaque format a ses propres nuances, mais tous nécessitent au minimum une invite de l'utilisateur.


**Champs obligatoires**  

| Champ | Obligatoire | 
| --- | --- | 
| Invite de l'utilisateur | Oui | 
| Invite système | Non | 
| Vérité fondamentale | Uniquement pour Custom Scorer | 
| Catégorie | Non | 

**1. Format OpenAI**

```
{
    "messages": [
        {
            "role": "system",    # System prompt (looks for system role)
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",       # Query (looks for user role)
            "content": "Hello!"
        },
        {
            "role": "assistant",  # Ground truth (looks for assistant role)
            "content": "Hello to you!"
        }
    ]
}
```

**2. SageMaker **Évaluation

```
{
   "system":"You are an English major with top marks in class who likes to give minimal word responses: ",
   "query":"What is the symbol that ends the sentence as a question",
   "response":"?", # Ground truth
   "category": "Grammar"
}
```

**3. HuggingFace Achèvement rapide**

Les formats standard et conversationnel sont pris en charge.

```
# Standard

{
    "prompt" : "What is the symbol that ends the sentence as a question", # Query
    "completion" : "?" # Ground truth
}

# Conversational
{
    "prompt": [
        {
            "role": "user", # Query (looks for user role)
            "content": "What is the symbol that ends the sentence as a question"
        }
    ],
    "completion": [
        {
            "role": "assistant", # Ground truth (looks for assistant role)
            "content": "?"
        }
    ]
}
```

**4. HuggingFace Préférence**

Support du format standard (chaîne) et du format conversationnel (tableau de messages).

```
# Standard: {"prompt": "text", "chosen": "text", "rejected": "text"}
{
     "prompt" : "The sky is", # Query
     "chosen" : "blue", # Ground truth
     "rejected" : "green"
}

# Conversational:
{
    "prompt": [
        {
            "role": "user", # Query (looks for user role)
            "content": "What color is the sky?"
        }
    ],
    "chosen": [
        {
            "role": "assistant", # Ground truth (looks for assistant role)
            "content": "It is blue."
        }
    ],
    "rejected": [
        {
            "role": "assistant",
            "content": "It is green."
        }
    ]
}
```

**5. Format Verl**

Le format Verl (formats actuels et anciens) est pris en charge pour les cas d'utilisation de l'apprentissage par renforcement. Documents Verl pour référence : [https://verl.readthedocs.io/en/latest/preparation/prepare\$1data.html](https://verl.readthedocs.io/en/latest/preparation/prepare_data.html)

Les utilisateurs du format VERL ne fournissent généralement pas de réponse fondée sur la vérité. Si vous souhaitez en fournir un de toute façon, utilisez l'un des champs `extra_info.answer` ou `reward_model.ground_truth` ; `extra_info` a priorité.

SageMaker préserve les champs spécifiques à Verl suivants sous forme de métadonnées, le cas échéant :
+ `id`
+ `data_source`
+ `ability`
+ `reward_model`
+ `extra_info`
+ `attributes`
+ `difficulty`

```
# Newest VERL format where `prompt` is an array of messages.
{
  "data_source": "openai/gsm8k",
  "prompt": [
    {
      "content": "You are a helpful math tutor who explains solutions to questions step-by-step.",
      "role": "system"
    },
    {
      "content": "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May? Let's think step by step and output the final answer after \"####\".",
      "role": "user"
    }
  ],
  "ability": "math",
  "extra_info": {
    "answer": "Natalia sold 48/2 = <<48/2=24>>24 clips in May.\nNatalia sold 48+24 = <<48+24=72>>72 clips altogether in April and May.\n#### 72",
    "index": 0,
    "question": "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?",
    "split": "train"
  },
  "reward_model": {
    "ground_truth": "72" # Ignored in favor of extra_info.answer
  }
}

# Legacy VERL format where `prompt` is a string. Also supported.
{
  "data_source": "openai/gsm8k",
  "prompt": "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May? Let's think step by step and output the final answer after \"####\".",
  "extra_info": {
    "answer": "Natalia sold 48/2 = <<48/2=24>>24 clips in May.\nNatalia sold 48+24 = <<48+24=72>>72 clips altogether in April and May.\n#### 72",
    "index": 0,
    "question": "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?",
    "split": "train"
  }
}
```

# Évaluez à l'aide de marqueurs prédéfinis et personnalisés
<a name="model-customize-evaluation-preset-custom-scorers"></a>

Lorsque vous utilisez le type d'évaluation Custom Scorer, SageMaker Evaluation prend en charge deux marqueurs intégrés (également appelés « fonctions de récompense ») Prime Math et Prime Code extraits de la bibliothèque d'entraînement [volcengine/verl RL](https://github.com/volcengine/verl), ou votre propre marqueur personnalisé implémenté sous forme de fonction Lambda.

## Scorers intégrés
<a name="model-customize-evaluation-builtin-scorers"></a>

**Prime Math**

Le meilleur marqueur mathématique attend un jeu de données JSONL personnalisé contenant une question mathématique prompt/query et la bonne réponse comme vérité de base. L'ensemble de données peut être dans l'un des formats pris en charge mentionnés dans[Formats de jeu de données pris en charge pour les tâches Bring-Your-Own-Dataset (BYOD)](model-customize-evaluation-dataset-formats.md).

Exemple d'entrée dans un jeu de données (développé pour plus de clarté) :

```
{
    "system":"You are a math expert: ",
    "query":"How many vertical asymptotes does the graph of $y=\\frac{2}{x^2+x-6}$ have?",
    "response":"2" # Ground truth aka correct answer
}
```

**Code Prime**

Le lecteur de code principal attend un ensemble de données JSONL personnalisé contenant des entrées contenant un problème de codage et des cas de test spécifiés dans le champ. `metadata` Structurez les scénarios de test avec le nom de fonction attendu pour chaque entrée, des exemples d'entrées et des sorties attendues.

Exemple d'entrée dans un jeu de données (développé pour plus de clarté) :

```
{
    "system":"\\nWhen tackling complex reasoning tasks, you have access to the following actions. Use them as needed to progress through your thought process.\\n\\n[ASSESS]\\n\\n[ADVANCE]\\n\\n[VERIFY]\\n\\n[SIMPLIFY]\\n\\n[SYNTHESIZE]\\n\\n[PIVOT]\\n\\n[OUTPUT]\\n\\nYou should strictly follow the format below:\\n\\n[ACTION NAME]\\n\\n# Your action step 1\\n\\n# Your action step 2\\n\\n# Your action step 3\\n\\n...\\n\\nNext action: [NEXT ACTION NAME]\\n\\n",
    "query":"A number N is called a factorial number if it is the factorial of a positive integer. For example, the first few factorial numbers are 1, 2, 6, 24, 120,\\nGiven a number N, the task is to return the list/vector of the factorial numbers smaller than or equal to N.\\nExample 1:\\nInput: N = 3\\nOutput: 1 2\\nExplanation: The first factorial number is \\n1 which is less than equal to N. The second \\nnumber is 2 which is less than equal to N,\\nbut the third factorial number is 6 which \\nis greater than N. So we print only 1 and 2.\\nExample 2:\\nInput: N = 6\\nOutput: 1 2 6\\nExplanation: The first three factorial \\nnumbers are less than equal to N but \\nthe fourth factorial number 24 is \\ngreater than N. So we print only first \\nthree factorial numbers.\\nYour Task:  \\nYou don't need to read input or print anything. Your task is to complete the function factorialNumbers() which takes an integer N as an input parameter and return the list/vector of the factorial numbers smaller than or equal to N.\\nExpected Time Complexity: O(K), Where K is the number of factorial numbers.\\nExpected Auxiliary Space: O(1)\\nConstraints:\\n1<=N<=10^{18}\\n\\nWrite Python code to solve the problem. Present the code in \\n```python\\nYour code\\n```\\nat the end.",
    "response": "", # Dummy string for ground truth. Provide a value if you want NLP metrics like ROUGE, BLEU, and F1.
    ### Define test cases in metadata field
    "metadata": {
        "fn_name": "factorialNumbers",
        "inputs": ["5"],
        "outputs": ["[1, 2]"]
    }
}
```

## Scorateurs personnalisés (apportez vos propres statistiques)
<a name="model-customize-evaluation-custom-scorers-byom"></a>

Personnalisez entièrement le flux de travail d'évaluation de votre modèle grâce à une logique de post-traitement personnalisée qui vous permet de calculer des métriques personnalisées adaptées à vos besoins. Vous devez implémenter votre score personnalisé sous la forme d'une fonction AWS Lambda qui accepte les réponses du modèle et renvoie les scores de récompense.

### Exemple de charge utile d'entrée Lambda
<a name="model-customize-evaluation-custom-scorers-lambda-input"></a>

Votre AWS Lambda personnalisé attend des entrées au format OpenAI. Exemple :

```
{
    "id": "123",
    "messages": [
        {
            "role": "user",
            "content": "Do you have a dedicated security team?"
        },
        {
            "role": "assistant",
            "content": "As an AI developed by Amazon, I do not have a dedicated security team..."
        }
    ],
    "reference_answer": {
        "compliant": "No",
        "explanation": "As an AI developed by Company, I do not have a traditional security team..."
    }
}
```

### Exemple de charge utile de sortie Lambda
<a name="model-customize-evaluation-custom-scorers-lambda-output"></a>

Le conteneur SageMaker d'évaluation s'attend à ce que vos réponses Lambda suivent le format suivant :

```
{
    "id": str,                              # Same id as input sample
    "aggregate_reward_score": float,        # Overall score for the sample
    "metrics_list": [                       # OPTIONAL: Component scores
        {
            "name": str,                    # Name of the component score
            "value": float,                 # Value of the component score
            "type": str                     # "Reward" or "Metric"
        }
    ]
}
```

### Définition Lambda personnalisée
<a name="model-customize-evaluation-custom-scorers-lambda-definition"></a>

Trouvez un exemple de scorer personnalisé entièrement implémenté avec des exemples d'entrées et de sorties attendues sur : [https://docs.aws.amazon.com/sagemaker/latest/dg/nova- implementing-reward-functions](https://docs.aws.amazon.com/sagemaker/latest/dg/nova-implementing-reward-functions.html#nova-reward-llm-judge-example) .html\$1 -example nova-reward-llm-judge

Utilisez le squelette suivant comme point de départ pour votre propre fonction.

```
def lambda_handler(event, context):
    return lambda_grader(event)

def lambda_grader(samples: list[dict]) -> list[dict]:
    """
    Args:
        Samples: List of dictionaries in OpenAI format
            
        Example input:
        {
            "id": "123",
            "messages": [
                {
                    "role": "user",
                    "content": "Do you have a dedicated security team?"
                },
                {
                    "role": "assistant",
                    "content": "As an AI developed by Company, I do not have a dedicated security team..."
                }
            ],
            # This section is the same as your training dataset
            "reference_answer": {
                "compliant": "No",
                "explanation": "As an AI developed by Company, I do not have a traditional security team..."
            }
        }
        
    Returns:
        List of dictionaries with reward scores:
        {
            "id": str,                              # Same id as input sample
            "aggregate_reward_score": float,        # Overall score for the sample
            "metrics_list": [                       # OPTIONAL: Component scores
                {
                    "name": str,                    # Name of the component score
                    "value": float,                 # Value of the component score
                    "type": str                     # "Reward" or "Metric"
                }
            ]
        }
    """
```

### Champs d'entrée et de sortie
<a name="model-customize-evaluation-custom-scorers-fields"></a>

**Champs de saisie**


| Champ | Description | Informations complémentaires | 
| --- | --- | --- | 
| id | Identifiant unique pour l'échantillon | Répertorié dans la sortie. Format de chaîne | 
| messages | Historique des discussions ordonné au format OpenAI | Tableau d'objets de message | 
| messages [] .role | Intervenant du message | Valeurs communes : « utilisateur », « assistant », « système » | 
| messages [] .content | Contenu textuel du message | Chaîne de texte brut | 
| metadata | Informations sous forme libre pour faciliter le classement | Objet ; champs facultatifs transmis à partir des données d'entraînement | 

**Champs de sortie**


**Champs de sortie**  

| Champ | Description | Informations complémentaires | 
| --- | --- | --- | 
| id | Identifiant identique à celui de l'échantillon d'entrée | Doit correspondre à l'entrée | 
| score de récompense agrégé | Note globale pour l'échantillon | Valeur flottante (par exemple, 0,0-1,0 ou plage définie par la tâche) | 
| liste\$1métriques | Scores des composants qui constituent l'agrégat | Tableau d'objets métriques | 

### Autorisations nécessaires
<a name="model-customize-evaluation-custom-scorers-permissions"></a>

Assurez-vous que le rôle SageMaker d'exécution que vous utilisez pour exécuter l'évaluation dispose des autorisations AWS Lambda.

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction"
            ],
            "Resource": "arn:aws:lambda:region:account-id:function:function-name"
        }
    ]
}
```

Assurez-vous que le rôle d'exécution de votre fonction AWS Lambda dispose des autorisations d'exécution Lambda de base, ainsi que des autorisations supplémentaires dont vous pourriez avoir besoin pour tout appel en aval. AWS 

```
{
  "Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    }
  ]
}
```

# Déploiement de modèles
<a name="model-customize-open-weight-deployment"></a>

Sur la page de détails des modèles personnalisés, vous pouvez également déployer votre modèle personnalisé à l'aide des points de terminaison SageMaker AI Inference ou d'Amazon Bedrock.

![\[Une image contenant une sélection de techniques de personnalisation du modèle.\]](http://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/images/screenshot-open-model-1.png)


# Exemples d'ensembles de données et d'évaluateurs
<a name="model-customize-open-weight-samples"></a>

## Réglage fin supervisé (SFT)
<a name="model-customize-open-weight-samples-sft"></a>
+ Nom : TAT-QA
+ Licence : CC-BY-4.0
+ Lien : [https://huggingface. co/datasets/next-tat/TAT-QA](https://huggingface.co/datasets/next-tat/TAT-QA)
+ Prétraitement - Formatage

**Un échantillon**

```
{
    "prompt": "Given a table and relevant text descriptions, answer the following question.\n\nTable:\n<table border=\"1\" class=\"dataframe\">\n  <tbody>\n    <tr>\n      <td></td>\n      <td>2019</td>\n      <td>2018</td>\n    </tr>\n    <tr>\n      <td></td>\n      <td>$'000</td>\n      <td>$'000</td>\n    </tr>\n    <tr>\n      <td>Revenue from external customers</td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <td>Australia</td>\n      <td>144,621</td>\n      <td>129,431</td>\n    </tr>\n    <tr>\n      <td>New Zealand</td>\n      <td>13,036</td>\n      <td>8,912</td>\n    </tr>\n    <tr>\n      <td>Total</td>\n      <td>157,657</td>\n      <td>138,343</td>\n    </tr>\n  </tbody>\n</table>\n\nParagraphs:\n    4. SEGMENT INFORMATION\n\n    During the 2019 and 2018 financial years, the Group operated wholly within one business segment being the operation and management of storage centres in Australia and New Zealand.\n\n    The Managing Director is the Group\u2019s chief operating decision maker and monitors the operating results on a portfolio wide basis. Monthly management reports are evaluated based upon the overall performance of NSR consistent with the presentation within the consolidated financial statements. The Group\u2019s financing (including finance costs and finance income) are managed on a Group basis and not allocated to operating segments.\n\n    The operating results presented in the statement of profit or loss represent the same segment information as reported in internal management information.\n\n    The revenue information above excludes interest income and is based on the location of storage centres.\n\nQuestion: How many business segments were present in 2019 and 2018?\n\nAnswer:",
    "completion": "one",
    "data_idx": "2951"
}
```

## Optimisation directe des préférences (DPO)
<a name="model-customize-open-weight-samples-dpo"></a>
+ Nom : Ultrafeedback
+ Licence : MIT
+ Lien : [https://huggingface. co/datasets/openbmb/UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback)
+ Étapes de prétraitement : formatage et sous-échantillonnage.

**Un échantillon**

```
{
    "source": "evol_instruct",
    "prompt": "Can you write a C++ program that prompts the user to enter the name of a country and checks if it borders the Mediterranean Sea? Here's some starter code to help you out:\n#include <iostream>\n#include <string>\nusing namespace std;\nint main() {\n    string country;\n    // prompt user for input\n    cout << \"Enter the name of a country: \";\n    cin >> country;\n    // check if country borders the Mediterranean Sea\n    // [C++ code]\n    return 0;\n}",
    "chosen": "Here's a C++ program that prompts the user to enter the name of a country and checks if it borders the Mediterranean Sea:\n\n#include <iostream>\n#include <string>\n#include <set>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n    // store countries and their bordering seas in a map\n    map<string, set<string>> countries;\n    countries[\"Algeria\"] = {\"Mediterranean Sea\", \"North African Coast\"};\n    countries[\"France\"] = {\"Mediterranean Sea\", \"English Channel\"};\n    countries[\"Italy\"] = {\"Mediterranean Sea\", \"Adriatic Sea\"};\n    countries[\"Malta\"] = {\"Mediterranean Sea\", \"North African Coast\"};\n    countries[\"Spain\"] = {\"Mediterranean Sea\", \"Atlantic Ocean\"};\n    countries[\"Tunisia\"] = {\"Mediterranean Sea\", \"North African Coast\"};\n\n    string country;\n    cout << \"Enter the name of a country: \";\n    cin >> country;\n\n    // check if country is in the map\n    if (countries.find(country)!= countries.end()) {\n        // check if country borders the Mediterranean Sea\n        set<string> borders = countries.at(country);\n        if (borders.find(\"Mediterranean Sea\")!= borders.end()) {\n            cout << country << \" borders the Mediterranean Sea.\" << endl;\n        } else {\n            cout << country << \" does not border the Mediterranean Sea.\" << endl;\n        }\n    } else {\n        cout << country << \" is not a recognized country.\" << endl;\n    }\n\n    return 0;\n}\n\nIn this program, we first define a map called countries that stores each country's name as a key and a set of its surrounding seas as the value. We use a set to store each sea name so that we can easily check if a country borders a certain sea.\n\nWe then present the user with a prompt to enter the name of a country. We use a while loop to ensure that the user enters a valid country name. We check if the country is in the map, and if so, we retrieve its bordering seas from the map.\n\nFinally, we check if the Mediterranean Sea is among the set of borders. If it is, we inform the user that the country borders the Mediterranean Sea. If not, we inform the user that the country does not border the Mediterranean Sea.",
    "chosen-rating": 5.0,
    "chosen-model": "starchat",
    "rejected": "Sure, here is the program using the C++11 algorithm \"cds::algorithm::GreaterEqual\":\n#include <iostream>\n#include <string>\n#include <algorithm>\n#include <vector>\n#include <cctype>\n\nusing namespace std;\n\nint main() {\n    string country;\n    cout << \"Enter the name of a country: \";\n    cin >> country;\n    std::vector<string> vec;\n    vec.push_back(country);\n    size_t index = std::find_if(vec.begin(), vec.end(), [](const string& s) {\n        return std::any_of(s.begin(), s.end(), [](const char& c) {\n            return c == '}}';\n    });\n    if (index != vec.end()) {\n        if ((*index)[0] == 'M') {\n            cout << \"Country is bordered by the Mediterranean Sea.\" << endl;\n        } else {\n            cout << \"Country does not border the Mediterranean Sea.\" << endl;\n        }\n    } else {\n        cout << \"Country is not found.\" << endl;\n    }\n    return 0;\n}",
    "rejected-rating": 1.25,
    "rejected-model": "pythia-12b"
}
```

## Apprentissage par renforcement à partir des commentaires liés à l'IA (RLAIF) - Jugement par paires
<a name="model-customize-open-weight-samples-rlaif"></a>

**Ensemble de données d'entrée**

Ensemble de données source : [https://github.com/WeOpenML/PandalM](https://github.com/WeOpenML/PandaLM)

**Un échantillon**

```
{
    "data_source": "WeOpenML/PandaLM",
    "prompt": [
        {
            "role": "user",
            "content": "Below are two responses for a given task. The task is defined by the Instruction with an Input that provides further context. Evaluate the responses and generate a reference answer for the task.\n\n
            ### Instruction:\nCompare the given products.\n\n### Input:\niPhone 11 and Google Pixel 4\n\n
            ### Response 1:\nThe iPhone 11 has a larger screen size and a longer battery life than the Google Pixel 4.\n\n
            ### Response 2:\nThe iPhone 11 and Google Pixel 4 are both flagship smartphones released in 2018. The iPhone 11 has a 6.1-inch LCD display, while the Google Pixel 4 has a 5.7-inch OLED display. The iPhone 11 has an A13 Bionic chipset, while the Google Pixel 4 has a Qualcomm Snapdragon 845 chipset. The iPhone 11 has a dual-camera system, while the Google Pixel 4 has a single camera system. The iPhone 11 has a longer battery life, while the Google Pixel 4 has a faster processor.\n\n### Evaluation:\n"
        }
    ],
    "ability": "pairwise-judging",
    "reward_model": {
        "style": "llmj",
        "ground_truth": "2\n\n### Reason: Response 2 provides a more detailed and comprehensive comparison of the two products, including their specifications and features. Response 1 only mentions two aspects of the products and does not provide as much information.\n\n### Reference: The iPhone 11 and Google Pixel 4 are both flagship smartphones released in 2018. The iPhone 11 has a 6.1-inch LCD display, while the Google Pixel 4 has a 5.7-inch OLED display. The iPhone 11 has an A13 Bionic chipset, while the Google Pixel 4 has a Qualcomm Snapdragon 845 chipset. The iPhone 11 has a dual-camera system, while the Google Pixel 4 has a single camera system. The iPhone 11 has a longer battery life, while the Google Pixel 4 has a faster processor."
    },
    "extra_info": {
        "split": "train",
        "index": 0,
        "raw_output_sequence": "2\n\n### Reason: Response 2 provides a more detailed and comprehensive comparison of the two products, including their specifications and features. Response 1 only mentions two aspects of the products and does not provide as much information.\n\n### Reference: The iPhone 11 and Google Pixel 4 are both flagship smartphones released in 2018. The iPhone 11 has a 6.1-inch LCD display, while the Google Pixel 4 has a 5.7-inch OLED display. The iPhone 11 has an A13 Bionic chipset, while the Google Pixel 4 has a Qualcomm Snapdragon 845 chipset. The iPhone 11 has a dual-camera system, while the Google Pixel 4 has a single camera system. The iPhone 11 has a longer battery life, while the Google Pixel 4 has a faster processor.\n",
        "llmj": {
            "question": "Below are two responses for a given task. The task is defined by the Instruction with an Input that provides further context. Evaluate the responses and generate a reference answer for the task.\n\n### Instruction:\nCompare the given products.\n\n### Input:\niPhone 11 and Google Pixel 4\n\n### Response 1:\nThe iPhone 11 has a larger screen size and a longer battery life than the Google Pixel 4.\n\n### Response 2:\nThe iPhone 11 and Google Pixel 4 are both flagship smartphones released in 2018. The iPhone 11 has a 6.1-inch LCD display, while the Google Pixel 4 has a 5.7-inch OLED display. The iPhone 11 has an A13 Bionic chipset, while the Google Pixel 4 has a Qualcomm Snapdragon 845 chipset. The iPhone 11 has a dual-camera system, while the Google Pixel 4 has a single camera system. The iPhone 11 has a longer battery life, while the Google Pixel 4 has a faster processor.\n\n### Evaluation:\n",
            "ground_truth": "2\n\n### Reason: Response 2 provides a more detailed and comprehensive comparison of the two products, including their specifications and features. Response 1 only mentions two aspects of the products and does not provide as much information.\n\n### Reference: The iPhone 11 and Google Pixel 4 are both flagship smartphones released in 2018. The iPhone 11 has a 6.1-inch LCD display, while the Google Pixel 4 has a 5.7-inch OLED display. The iPhone 11 has an A13 Bionic chipset, while the Google Pixel 4 has a Qualcomm Snapdragon 845 chipset. The iPhone 11 has a dual-camera system, while the Google Pixel 4 has a single camera system. The iPhone 11 has a longer battery life, while the Google Pixel 4 has a faster processor.",
            "document_in_context": null
        },
        "sample_size": 1980
    }
}
```

## RLAIF - Chaîne de pensée
<a name="model-customize-open-weight-samples-rlaif2"></a>

**Ensemble de données d'entrée**

Données sources : [https://huggingface. co/datasets/thesven/gsm8k-reasoning/tree/main/data](https://huggingface.co/datasets/thesven/gsm8k-reasoning/tree/main/data)

**Un échantillon**

```
{
    "data_source": "openai/gsm8k",
    "prompt": [
        {
            "role": "system",
            "content": "\nYou are an AI assistant that uses a Chain of Thought (CoT) approach with reflection to answer queries.\n\nFollow these steps:\n- Think through the problem step by step within the ‹thinking> tags.\n- Reflect on your thinking\n\nto check for any errors or improvements within the ‹reflection› tags.\n- Make any necessary adjustments based on your reflection.\n- Provide your final, concise answer within the ‹output> tags.\n\nImportant: The <thinking> and ‹reflection› sections are for your internal reasoning process only.\nDo not include any part of the final answer in these sections.\nThe actual response to the query must be entirely contained within the ‹output› tags.\n\nUse the following format for your response:\n<thinking>\n[Your initial thought process goes here]\n</thinking›\n\n<reasoning>\n[Your step-by-step reasoning goes here. This is your internal thought process, not the final answer. You can create as many reasoning steps as necessary in your process.]\n</reasoning>\n\n‹reflection>\n[Your reflection on your reasoning, checking for errors or improvements. You can create as many reflection steps as necessary in your process.]\n</ reflection>\n\n<adjustment>\n[Any adjustments to your thinking based on your reflection]\n</adjustment>\n\n<output>\n[Your final, concise answer to the query. This is the only part that will be shown to the user.]\n</output>\n"
        },
        {
            "role": "user",
            "content": "A craft store makes a third of its sales in the fabric section, a quarter of its sales in the jewelry section, and the rest in the stationery section. They made 36 sales today. How many sales were in the stationery section?"
        }
    ],
    "ability": "chain-of-thought",
    "reward_model": {
        "style": "llmj-cot",
        "ground_truth": "Thus, there were 36 - 12 - 9 = <<36-12-9=15>>15 sales in the stationery section."
    },
    "extra_info": {
        "split": "train",
        "index": 0,
        "question": "A craft store makes a third of its sales in the fabric section, a quarter of its sales in the jewelry section, and the rest in the stationery section. They made 36 sales today. How many sales were in the stationery section?",
        "short_answer": "15",
        "model_output": "<thinking>\nTo find the number of sales in the stationery section, I need to first calculate the number of sales in the fabric and jewelry sections. The store makes a third of its sales in the fabric section, which is 1/3 of 36 sales. I can calculate this as 36 * 1/3 = 12 sales in the fabric section. The store makes a quarter of its sales in the jewelry section, which is 1/4 of 36 sales. I can calculate this as 36 * 1/4 = 9 sales in the jewelry section. Since the rest of the sales are in the stationery section, I can subtract the sales from the other two sections from the total number of sales to find the number of sales in the stationery section.\n</thinking>\n\n<reasoning>\n1. Calculate the number of sales in the fabric section: 36 * 1/3 = 12\n2. Calculate the number of sales in the jewelry section: 36 * 1/4 = 9\n3. Calculate the number of sales in the stationery section: 36 - 12 - 9 = 15\n</reasoning>\n\n‹reflection>\nUpon reviewing my reasoning, I noticed that my calculations seem correct, but I should ensure that I understand the question correctly. The question asks for the number of sales in the stationery section, and I believe I have correctly calculated that. However, I should double-check my math to make sure it's accurate.\n</reflection>\n\n<adjustment>\nUpon re-examining my math, I am confident that my calculations are correct. The fabric section makes up 1/3 of the sales, the jewelry section makes up 1/4, and the rest is the stationery section. My math checks out, and I am confident in my answer.\n</adjustment>\n\n<output>\n15\n</output>"
    }
}
```

## RAPIF - Fidélité
<a name="model-customize-open-weight-samples-rlaif3"></a>

**Ensemble de données d'entrée**

Une source : [https://huggingface. co/datasets/rajpurkar/squad\$1v2/blob/main/squad\$1v2/train](https://huggingface.co/datasets/rajpurkar/squad_v2/blob/main/squad_v2/train-00000-of-00001.parquet)-00000-of-00001.parquet

**Un échantillon**

```
{
    "data_source": "squad_v2",
    "prompt": [
        {
            "role": "system",
            "content": "You are a helpful assistant that answers questions based on the provided context. Only use information from the context."
        },
        {
            "role": "user",
            "content": "Context: Beyoncé Giselle Knowles-Carter (/biːˈjɒnseɪ/ bee-YON-say) (born September 4, 1981) is an American singer, songwriter, record producer and actress. Born and raised in Houston, Texas, she performed in various singing and dancing competitions as a child, and rose to fame in the late 1990s as lead singer of R&B girl-group Destiny's Child. Managed by her father, Mathew Knowles, the group became one of the world's best-selling girl groups of all time. Their hiatus saw the release of Beyoncé's debut album, Dangerously in Love (2003), which established her as a solo artist worldwide, earned five Grammy Awards and featured the Billboard Hot 100 number-one singles \"Crazy in Love\" and \"Baby Boy\".\n\nQuestion: When did Beyonce start becoming popular?"
        }
    ],
    "ability": "faithfulness",
    "reward_model": {
        "style": "llmj-faithfulness",
        "ground_truth": "Beyoncé Giselle Knowles-Carter (/biːˈjɒnseɪ/ bee-YON-say) (born September 4, 1981) is an American singer, songwriter, record producer and actress. Born and raised in Houston, Texas, she performed in various singing and dancing competitions as a child, and rose to fame in the late 1990s as lead singer of R&B girl-group Destiny's Child. Managed by her father, Mathew Knowles, the group became one of the world's best-selling girl groups of all time. Their hiatus saw the release of Beyoncé's debut album, Dangerously in Love (2003), which established her as a solo artist worldwide, earned five Grammy Awards and featured the Billboard Hot 100 number-one singles \"Crazy in Love\" and \"Baby Boy\"."
    },
    "extra_info": {
        "question": "When did Beyonce start becoming popular?",
        "split": "train",
        "index": 0
    }
}
```

## RLAIF - Résumé
<a name="model-customize-open-weight-samples-rlaif4"></a>

**Ensemble de données d'entrée**

[Source : ensemble de données gsm8k nettoyé https://huggingface. co/datasets/thesven/gsm8k-reasoning/tree/main/data](https://huggingface.co/datasets/thesven/gsm8k-reasoning/tree/main/data)

**Un échantillon**

```
{
    "data_source": "cnn_dailymail",
    "prompt": [
        {
            "role": "system",
            "content": "You are a helpful assistant that creates concise, accurate summaries of news articles. Focus on the key facts and main points."
        },
        {
            "role": "user",
            "content": "Summarize the following article:\n\nLONDON, England (Reuters) -- Harry Potter star Daniel Radcliffe gains access to a reported £20 million ($41.1 million) fortune as he turns 18 on Monday, but he insists the money won't cast a spell on him. Daniel Radcliffe as Harry Potter in \"Harry Potter and the Order of the Phoenix\" To the disappointment of gossip columnists around the world, the young actor says he has no plans to fritter his cash away on fast cars, drink and celebrity parties. \"I don't plan to be one of those people who, as soon as they turn 18, suddenly buy themselves a massive sports car collection or something similar,\" he told an Australian interviewer earlier this month. \"I don't think I'll be particularly extravagant. \"The things I like buying are things that cost about 10 pounds -- books and CDs and DVDs.\" At 18, Radcliffe will be able to gamble in a casino, buy a drink in a pub or see the horror film \"Hostel: Part II,\" currently six places below his number one movie on the UK box office chart. Details of how he'll mark his landmark birthday are under wraps. His agent and publicist had no comment on his plans. \"I'll definitely have some sort of party,\" he said in an interview. \"Hopefully none of you will be reading about it.\" Radcliffe's earnings from the first five Potter films have been held in a trust fund which he has not been able to touch. Despite his growing fame and riches, the actor says he is keeping his feet firmly on the ground. \"People are always looking to say 'kid star goes off the rails,'\" he told reporters last month. \"But I try very hard not to go that way because it would be too easy for them.\" His latest outing as the boy wizard in \"Harry Potter and the Order of the Phoenix\" is breaking records on both sides of the Atlantic and he will reprise the role in the last two films.  Watch I-Reporter give her review of Potter's latest » . There is life beyond Potter, however. The Londoner has filmed a TV movie called \"My Boy Jack,\" about author Rudyard Kipling and his son, due for release later this year. He will also appear in \"December Boys,\" an Australian film about four boys who escape an orphanage. Earlier this year, he made his stage debut playing a tortured teenager in Peter Shaffer's \"Equus.\" Meanwhile, he is braced for even closer media scrutiny now that he's legally an adult: \"I just think I'm going to be more sort of fair game,\" he told Reuters. E-mail to a friend . Copyright 2007 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed."
        }
    ],
    "ability": "summarization",
    "reward_model": {
        "style": "llmj-summarization",
        "ground_truth": "Harry Potter star Daniel Radcliffe gets £20M fortune as he turns 18 Monday .\nYoung actor says he has no plans to fritter his cash away .\nRadcliffe's earnings from first five Potter films have been held in trust fund ."
    },
    "extra_info": {
        "question": "LONDON, England (Reuters) -- Harry Potter star Daniel Radcliffe gains access to a reported £20 million ($41.1 million) fortune as he turns 18 on Monday, but he insists the money won't cast a spell on him. Daniel Radcliffe as Harry Potter in \"Harry Potter and the Order of the Phoenix\" To the disappointment of gossip columnists around the world, the young actor says he has no plans to fritter his cash away on fast cars, drink and celebrity parties. \"I don't plan to be one of those people who, as soon as they turn 18, suddenly buy themselves a massive sports car collection or something similar,\" he told an Australian interviewer earlier this month. \"I don't think I'll be particularly extravagant. \"The things I like buying are things that cost about 10 pounds -- books and CDs and DVDs.\" At 18, Radcliffe will be able to gamble in a casino, buy a drink in a pub or see the horror film \"Hostel: Part II,\" currently six places below his number one movie on the UK box office chart. Details of how he'll mark his landmark birthday are under wraps. His agent and publicist had no comment on his plans. \"I'll definitely have some sort of party,\" he said in an interview. \"Hopefully none of you will be reading about it.\" Radcliffe's earnings from the first five Potter films have been held in a trust fund which he has not been able to touch. Despite his growing fame and riches, the actor says he is keeping his feet firmly on the ground. \"People are always looking to say 'kid star goes off the rails,'\" he told reporters last month. \"But I try very hard not to go that way because it would be too easy for them.\" His latest outing as the boy wizard in \"Harry Potter and the Order of the Phoenix\" is breaking records on both sides of the Atlantic and he will reprise the role in the last two films.  Watch I-Reporter give her review of Potter's latest » . There is life beyond Potter, however. The Londoner has filmed a TV movie called \"My Boy Jack,\" about author Rudyard Kipling and his son, due for release later this year. He will also appear in \"December Boys,\" an Australian film about four boys who escape an orphanage. Earlier this year, he made his stage debut playing a tortured teenager in Peter Shaffer's \"Equus.\" Meanwhile, he is braced for even closer media scrutiny now that he's legally an adult: \"I just think I'm going to be more sort of fair game,\" he told Reuters. E-mail to a friend . Copyright 2007 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed.",
        "split": "train",
        "index": 0,
        "source_id": "42c027e4ff9730fbb3de84c1af0d2c50"
    }
}
```

## RLAIF - Invite personnalisée
<a name="model-customize-open-weight-samples-rlaif5"></a>

Dans cet exemple, nous expliquons [RLAIF - Chaîne de pensée](#model-customize-open-weight-samples-rlaif2) comment une invite personnalisée de jinja peut remplacer l'une des instructions prédéfinies.

**Vous trouverez ci-dessous un exemple d'invite personnalisée pour CoT :**

```
You are an expert logical reasoning evaluator specializing in Chain-of-Thought (CoT) analysis. 

Given: A problem prompt and a model's reasoning-based response. 

Goal: Assess the quality and structure of logical reasoning, especially for specialized domains (law, medicine, finance, etc.).

Scoring rubric (start at 0.0, then add or subtract):

Core Components:

Structural Completeness (0.3 max)
- Clear problem statement: +0.05
- Defined variables/terminology: +0.05
- Organized given information: +0.05
- Explicit proof target: +0.05
- Step-by-step reasoning: +0.05
- Clear conclusion: +0.05

Logical Quality (0.4 max)
- Valid logical flow: +0.1
- Proper use of if-then relationships: +0.1
- Correct application of domain principles: +0.1
- No logical fallacies: +0.1

Technical Accuracy (0.3 max)
- Correct use of domain terminology: +0.1
- Accurate application of domain rules: +0.1
- Proper citation of relevant principles: +0.1

Critical Deductions:
A. Invalid logical leap: -0.3
B. Missing critical steps: -0.2
C. Incorrect domain application: -0.2
D. Unclear/ambiguous reasoning: -0.1

Additional Instructions:
- Verify domain-specific terminology and principles
- Check for logical consistency throughout
- Ensure conclusions follow from premises
- Flag potential domain-specific compliance issues
- Consider regulatory/professional standards where applicable

Return EXACTLY this JSON (no extra text):
{
    "score": <numerical score 0.0-1.0>,
    "component_scores": {
        "structural_completeness": <score>,
        "logical_quality": <score>,
        "technical_accuracy": <score>
    },
    "steps_present": {
        "problem_statement": <true/false>,
        "variable_definitions": <true/false>,
        "given_information": <true/false>,
        "proof_target": <true/false>,
        "step_reasoning": <true/false>,
        "conclusion": <true/false>
    },
    "reasoning": "<explain scoring decisions and identify any logical gaps>",
    "domain_flags": ["<any domain-specific concerns or compliance issues>"]
}

### (Prompt field from dataset)
Problem Prompt: {{ prompt }}

Model's Response: {{ model_output }}

### Ground truth (if applicable):
{{ ground_truth }}
```

## Apprentissage par renforcement grâce à des récompenses vérifiables (RLVR) - Exact Match
<a name="model-customize-open-weight-samples-RLVR"></a>

**Ensemble de données d'entrée**

Une source : [https://huggingface. co/datasets/openai/gsm8 km](https://huggingface.co/datasets/openai/gsm8k)

**Exemple**

```
{
  "data_source": "openai/gsm8k",
  "prompt": [
    {
      "content": "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May? Let\'s think step by step and output the final answer after \\"####\\".",
      "role": "user"
    }
  ],
  "ability": "math",
  "reward_model": {
    "ground_truth": "72",
    "style": "rule"
  },
  "extra_info": {
    "answer": "Natalia sold 48\\/2 = <<48\\/2=24>>24 clips in May.\\nNatalia sold 48+24 = <<48+24=72>>72 clips altogether in April and May.\\n#### 72",
    "index": 0,
    "question": "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?",
    "split": "train"
  }
}
```

## RLVR - Exécution de code
<a name="model-customize-open-weight-samples-RLVR2"></a>

**Ensemble de données d'entrée**

Une source : [https://huggingface. co/datasets/open-r1/codeforces](https://huggingface.co/datasets/open-r1/codeforces)

**Exemple**

```
{
  "data_source": "codeforces",
  "prompt": [
    {
      "content": "\nWhen tackling complex reasoning tasks, you have access to the following actions. Use them as needed to progress through your thought process.\n\n[ASSESS]\n\n[ADVANCE]\n\n[VERIFY]\n\n[SIMPLIFY]\n\n[SYNTHESIZE]\n\n[PIVOT]\n\n[OUTPUT]\n\nYou should strictly follow the format below:\n\n[ACTION NAME]\n\n# Your action step 1\n\n# Your action step 2\n\n# Your action step 3\n\n...\n\nNext action: [NEXT ACTION NAME]\n\n",
      "role": "system"
    },
    {
      "content": "Title: Zebras\n\nTime Limit: None seconds\n\nMemory Limit: None megabytes\n\nProblem Description:\nOleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.\n\nOleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.\n\nInput Specification:\nIn the only line of input data there is a non-empty string *s* consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |*s*|) does not exceed 200<=000 characters.\n\nOutput Specification:\nIf there is a way to divide history into zebra subsequences, in the first line of output you should print an integer *k* (1<=\u2264<=*k*<=\u2264<=|*s*|), the resulting number of subsequences. In the *i*-th of following *k* lines first print the integer *l**i* (1<=\u2264<=*l**i*<=\u2264<=|*s*|), which is the length of the *i*-th subsequence, and then *l**i* indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to *n* must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1.\n\nSubsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of *k*.\n\nDemo Input:\n['0010100\\n', '111\\n']\n\nDemo Output:\n['3\\n3 1 3 4\\n3 2 5 6\\n1 7\\n', '-1\\n']\n\nNote:\nnone\n\nWrite Python code to solve the problem. Present the code in \n```python\nYour code\n```\nat the end.",
      "role": "user"
    }
  ],
  "ability": "code",
  "reward_model": {
    "ground_truth": "{\"inputs\": [\"0010100\", \"111\", \"0\", \"1\", \"0101010101\", \"010100001\", \"000111000\", \"0101001000\", \"0000001000\", \"0101\", \"000101110\", \"010101010\", \"0101001010\", \"0100101100\", \"0110100000\", \"0000000000\", \"1111111111\", \"0010101100\", \"1010000\", \"0001110\", \"0000000000011001100011110101000101000010010111000100110110000011010011110110001100100001001001010010\", \"01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010\", \"0010011100000000\"], \"outputs\": [\"3\\n1 1\\n5 2 3 4 5 6\\n1 7\", \"-1\", \"1\\n1 1\", \"-1\", \"-1\", \"-1\", \"3\\n3 1 6 7\\n3 2 5 8\\n3 3 4 9\", \"4\\n5 1 2 3 4 5\\n3 6 7 8\\n1 9\\n1 10\", \"8\\n1 1\\n1 2\\n1 3\\n1 4\\n1 5\\n3 6 7 8\\n1 9\\n1 10\", \"-1\", \"-1\", \"1\\n9 1 2 3 4 5 6 7 8 9\", \"2\\n5 1 2 3 4 5\\n5 6 7 8 9 10\", \"2\\n5 1 2 3 8 9\\n5 4 5 6 7 10\", \"-1\", \"10\\n1 1\\n1 2\\n1 3\\n1 4\\n1 5\\n1 6\\n1 7\\n1 8\\n1 9\\n1 10\", \"-1\", \"2\\n3 1 8 9\\n7 2 3 4 5 6 7 10\", \"-1\", \"-1\", \"22\\n1 1\\n1 2\\n1 3\\n1 4\\n1 5\\n1 6\\n1 7\\n1 8\\n7 9 24 25 26 27 28 29\\n7 10 13 14 17 18 23 30\\n11 11 12 15 16 19 22 31 32 33 34 35\\n3 20 21 36\\n3 37 46 47\\n9 38 39 40 45 48 57 58 75 76\\n17 41 42 43 44 49 50 51 54 55 56 59 72 73 74 77 80 81\\n9 52 53 60 71 78 79 82 83 84\\n7 61 64 65 66 67 70 85\\n5 62 63 68 69 86\\n3 87 88 89\\n3 90 91 92\\n5 93 94 95 96 97\\n3 98 99 100\", \"1\\n245 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 ...\", \"8\\n3 1 8 9\\n5 2 3 4 7 10\\n3 5 6 11\\n1 12\\n1 13\\n1 14\\n1 15\\n1 16\"]}",
    "style": "rule"
  },
  "extra_info": {
    "index": 49,
    "split": "train"
  }
}
```

**Fonction de récompense**

Fonction de récompense : [https://github.com/volcengine/verl/tree/main/verl/utils/reward\$1score/prime\$1code](https://github.com/volcengine/verl/tree/main/verl/utils/reward_score/prime_code)

## RLVR - Réponse mathématique
<a name="model-customize-open-weight-samples-RLVR3"></a>

**Ensemble de données d'entrée**

[Source : ensemble de données gsm8k nettoyé https://huggingface. co/datasets/thesven/gsm8k-reasoning/tree/main/data](https://huggingface.co/datasets/thesven/gsm8k-reasoning/tree/main/data)

**Exemple**

```
[
    {
        "content": "\nYou are an AI assistant that uses a Chain of Thought (CoT) approach with reflection to answer queries...",
        "role": "system"
    },
    {
        "content": "A craft store makes a third of its sales in the fabric section, a quarter of its sales in the jewelry section, and the rest in the stationery section. They made 36 sales today. How many sales were in the stationery section?",
        "role": "user"
    },
    {
        "content": "\nTo find the number of sales in the stationery section, I need to first calculate the number of sales in the fabric and jewelry sections...\n\n\n<reasoning>\n1. Calculate the number of sales in the fabric section: 36 * 1/3 = 12\n2. Calculate the number of sales in the jewelry section: 36 * 1/4 = 9\n3. Calculate the number of sales in the stationery section: 36 - 12 - 9 = 15\n</reasoning>\n\n<reflection>\nUpon reviewing my reasoning, I noticed that my calculations seem correct...\n</reflection>\n\n<adjustment>\nUpon re-examining my math, I am confident that my calculations are correct...\n</adjustment>\n\n<output>\n15\n</output>",
        "role": "assistant"
    }
]
```

**Calcul de la récompense**

Fonction de récompense : [https://github.com/volcengine/verl/blob/main/verl/utils/reward\$1score/gsm8k.py](https://github.com/volcengine/verl/blob/main/verl/utils/reward_score/gsm8k.py)

## RLVR - Lambda personnalisé
<a name="model-customize-open-weight-samples-RLVR4"></a>

**Ensemble de données d'entrée**

[Source : ensemble de données gsm8k nettoyé https://huggingface. co/datasets/thesven/gsm8k-reasoning/tree/main/data](https://huggingface.co/datasets/thesven/gsm8k-reasoning/tree/main/data)

**Exemple**

```
[
  {
    "content": "\nYou are an AI assistant that uses a Chain of Thought (CoT) approach with reflection to answer queries.\n\nFollow these steps:\n- Think through the problem step by step within the ‹thinking> tags.\n- Reflect on your thinking\n\nto check for any errors or improvements within the ‹reflection› tags.\n- Make any necessary adjustments based on your reflection.\n- Provide your final, concise answer within the ‹output> tags.\n\nImportant: The <thinking> and ‹reflection› sections are for your internal reasoning process only.\nDo not include any part of the final answer in these sections.\nThe actual response to the query must be entirely contained within the ‹output› tags.\n\nUse the following format for your response:\n<thinking>\n[Your initial thought process goes here]\n</thinking›\n\n<reasoning>\n[Your step-by-step reasoning goes here. This is your internal thought process, not the final answer. You can create as many reasoning steps as necessary in your process.]\n</reasoning>\n\n‹reflection>\n[Your reflection on your reasoning, checking for errors or improvements. You can create as many reflection steps as necessary in your process.]\n</ reflection>\n\n<adjustment>\n[Any adjustments to your thinking based on your reflection]\n</adjustment>\n\n<output>\n[Your final, concise answer to the query. This is the only part that will be shown to the user.]\n</output>\n",
    "role": "system"
  },
  {
    "content": "A craft store makes a third of its sales in the fabric section, a quarter of its sales in the jewelry section, and the rest in the stationery section. They made 36 sales today. How many sales were in the stationery section?",
    "role": "user"
  },
  {
    "content": "<thinking>\nTo find the number of sales in the stationery section, I need to first calculate the number of sales in the fabric and jewelry sections. The store makes a third of its sales in the fabric section, which is 1/3 of 36 sales. I can calculate this as 36 * 1/3 = 12 sales in the fabric section. The store makes a quarter of its sales in the jewelry section, which is 1/4 of 36 sales. I can calculate this as 36 * 1/4 = 9 sales in the jewelry section. Since the rest of the sales are in the stationery section, I can subtract the sales from the other two sections from the total number of sales to find the number of sales in the stationery section.\n</thinking>\n\n<reasoning>\n1. Calculate the number of sales in the fabric section: 36 * 1/3 = 12\n2. Calculate the number of sales in the jewelry section: 36 * 1/4 = 9\n3. Calculate the number of sales in the stationery section: 36 - 12 - 9 = 15\n</reasoning>\n\n‹reflection>\nUpon reviewing my reasoning, I noticed that my calculations seem correct, but I should ensure that I understand the question correctly. The question asks for the number of sales in the stationery section, and I believe I have correctly calculated that. However, I should double-check my math to make sure it's accurate.\n</reflection>\n\n<adjustment>\nUpon re-examining my math, I am confident that my calculations are correct. The fabric section makes up 1/3 of the sales, the jewelry section makes up 1/4, and the rest is the stationery section. My math checks out, and I am confident in my answer.\n</adjustment>\n\n<output>\n15\n</output>",
    "role": "assistant"
  }
]
```

**Exemple de calcul de récompense**

```
# RLVR Evaluator for OSS

# lambda_grader.py
import json
import re
import uuid
from typing import Any, Dict, List
 
def custom_reward(assistant_answer: str, ground_truth: str) -> float:
    """
    Add custom reward computation here
 
    Example:-
    Reward = fraction of ground-truth words that are correct
    in the correct position.
 
    Example:
      gt:   "the cat sat"
      ans:  "the dog sat"
 
      word-by-word:
        "the" == "the"  -> correct
        "dog" != "cat"  -> wrong
        "sat" == "sat"  -> correct
 
      correct = 2 out of 3 -> reward = 2/3 ≈ 0.67
    """
    ans_words = assistant_answer.strip().lower().split()
    gt_words = ground_truth.strip().lower().split()
 
    if not gt_words:
        return 0.0
 
    correct = 0
    for aw, gw in zip(ans_words, gt_words):
        if aw == gw:
            correct += 1
 
    return correct / len(gt_words)
 
 
# Lambda utility functions
def _ok(body: Any, code: int = 200) -> Dict[str, Any]:
    return {
        "statusCode": code,
        "headers": {
            "content-type": "application/json",
            "access-control-allow-origin": "*",
            "access-control-allow-methods": "POST,OPTIONS",
            "access-control-allow-headers": "content-type",
        },
        "body": json.dumps(body),
    }
 
def _assistant_text(sample: Dict[str, Any]) -> str:
    """Extract assistant text from sample messages."""
    for m in reversed(sample.get("messages", [])):
        if m.get("role") == "assistant":
            return (m.get("content") or "").strip()
    return ""
 
def _sample_id(sample: Dict[str, Any]) -> str:
    """Generate or extract sample ID."""
    if isinstance(sample.get("id"), str) and sample["id"]:
        return sample["id"]
 
    return str(uuid.uuid4())
 
def _ground_truth(sample: Dict[str, Any]) -> str:
    """Extract ground truth from sample or metadata if available"""
 
    if isinstance(sample.get("reference_answer"), str) and sample["reference_answer"]:
        return sample["reference_answer"].strip()
 
    md = sample.get("metadata") or {}
    gt = md.get("reference_answer", None) or md.get("ground_truth", None)
    if gt is None:
        return ""
    return str(gt).strip()
 
 
def _score_and_metrics(sample: Dict[str, Any]) -> Dict[str, Any]:
    sid = _sample_id(sample)
    solution_text = _assistant_text(sample)
 
    # Extract ground truth
    gt = _ground_truth(sample)
 
    metrics_list: List[Dict[str, Any]] = []
 
    # Custom rlvr scoring
    if solution_text and gt:
        
        # Compute score
        reward_score = custom_reward(
            assistant_answer=solution_text,
            ground_truth=gt
        )
        
        # Add detailed metrics
        metrics_list.append({
            "name": "custom_reward_score", 
            "value": float(reward_score), 
            "type": "Reward"
        })
       
        # The aggregate reward score is the custom reward score
        aggregate_score = float(reward_score)
        
    else:
        # No solution text or ground truth - default to 0
        aggregate_score = 0.0
        metrics_list.append({
            "name": "default_zero", 
            "value": 0.0, 
            "type": "Reward"
        })
    print("detected score", {
        "id": sid,
        "aggregate_reward_score": float(aggregate_score),
        "metrics_list": metrics_list,
    })
    return {
        "id": sid,
        "aggregate_reward_score": float(aggregate_score),
        "metrics_list": metrics_list,
    }
 
def lambda_handler(event, context):
    """AWS Lambda handler for custom reward lambda grading."""
    # CORS preflight
    if event.get("requestContext", {}).get("http", {}).get("method") == "OPTIONS":
        return _ok({"ok": True})
 
    # Body may be a JSON string (API GW/Function URL) or already a dict (Invoke)
    raw = event.get("body") or "{}"
    try:
        body = json.loads(raw) if isinstance(raw, str) else raw
    except Exception as e:
        return _ok({"error": f"invalid JSON body: {e}"}, 400)
 
    # Accept top-level list, {"batch":[...]}, or single sample object
    if isinstance(body, dict) and isinstance(body.get("batch"), list):
        samples = body["batch"]
    else:
        return _ok({
            "error": "Send a sample object, or {'batch':[...]} , or a top-level list of samples."
        }, 400)
 
    try:
        results = [_score_and_metrics(s) for s in samples]
    except Exception as e:
        return _ok({"error": f"Custom scoring failed: {e}"}, 500)
 
    return _ok(results)
```

**Exemple de code de fonction de récompense**

```
# RLVR Evaluator for OSS
# lambda_grader.py

import json
import re
import uuid from typing 
import Any, Dict, List
 
def custom_reward(assistant_answer: str, ground_truth: str) -> float:
    """
    Add custom reward computation here
 
    Example:-
    Reward = fraction of ground-truth words that are correct
    in the correct position.
 
    Example:
      gt:   "the cat sat"
      ans:  "the dog sat"
 
      word-by-word:
        "the" == "the"  -> correct
        "dog" != "cat"  -> wrong
        "sat" == "sat"  -> correct
 
      correct = 2 out of 3 -> reward = 2/3 ≈ 0.67
    """
    ans_words = assistant_answer.strip().lower().split()
    gt_words = ground_truth.strip().lower().split()
 
    if not gt_words:
        return 0.0
 
    correct = 0
    for aw, gw in zip(ans_words, gt_words):
        if aw == gw:
            correct += 1
 
    return correct / len(gt_words)
 
 
# Lambda utility functions
def _ok(body: Any, code: int = 200) -> Dict[str, Any]:
    return {
        "statusCode": code,
        "headers": {
            "content-type": "application/json",
            "access-control-allow-origin": "*",
            "access-control-allow-methods": "POST,OPTIONS",
            "access-control-allow-headers": "content-type",
        },
        "body": json.dumps(body),
    }
 
def _assistant_text(sample: Dict[str, Any]) -> str:
    """Extract assistant text from sample messages."""
    for m in reversed(sample.get("messages", [])):
        if m.get("role") == "assistant":
            return (m.get("content") or "").strip()
    return ""
 
def _sample_id(sample: Dict[str, Any]) -> str:
    """Generate or extract sample ID."""
    if isinstance(sample.get("id"), str) and sample["id"]:
        return sample["id"]
 
    return str(uuid.uuid4())
 
def _ground_truth(sample: Dict[str, Any]) -> str:
    """Extract ground truth from sample or metadata if available"""
 
    if isinstance(sample.get("reference_answer"), str) and sample["reference_answer"]:
        return sample["reference_answer"].strip()
 
    md = sample.get("metadata") or {}
    gt = md.get("reference_answer", None) or md.get("ground_truth", None)
    if gt is None:
        return ""
    return str(gt).strip()
 
 
def _score_and_metrics(sample: Dict[str, Any]) -> Dict[str, Any]:
    sid = _sample_id(sample)
    solution_text = _assistant_text(sample)
 
    # Extract ground truth
    gt = _ground_truth(sample)
 
    metrics_list: List[Dict[str, Any]] = []
 
    # Custom rlvr scoring
    if solution_text and gt:
        
        # Compute score
        reward_score = custom_reward(
            assistant_answer=solution_text,
            ground_truth=gt
        )
        
        # Add detailed metrics
        metrics_list.append({
            "name": "custom_reward_score", 
            "value": float(reward_score), 
            "type": "Reward"
        })
       
        # The aggregate reward score is the custom reward score
        aggregate_score = float(reward_score)
        
    else:
        # No solution text or ground truth - default to 0
        aggregate_score = 0.0
        metrics_list.append({
            "name": "default_zero", 
            "value": 0.0, 
            "type": "Reward"
        })
    print("detected score", {
        "id": sid,
        "aggregate_reward_score": float(aggregate_score),
        "metrics_list": metrics_list,
    })
    return {
        "id": sid,
        "aggregate_reward_score": float(aggregate_score),
        "metrics_list": metrics_list,
    }
 
def lambda_handler(event, context):
    """AWS Lambda handler for custom reward lambda grading."""
    # CORS preflight
    if event.get("requestContext", {}).get("http", {}).get("method") == "OPTIONS":
        return _ok({"ok": True})
 
    # Body may be a JSON string (API GW/Function URL) or already a dict (Invoke)
    raw = event.get("body") or "{}"
    try:
        body = json.loads(raw) if isinstance(raw, str) else raw
    except Exception as e:
        return _ok({"error": f"invalid JSON body: {e}"}, 400)
 
    # Accept top-level list, {"batch":[...]}, or single sample object
    if isinstance(body, dict) and isinstance(body.get("batch"), list):
        samples = body["batch"]
    else:
        return _ok({
            "error": "Send a sample object, or {'batch':[...]} , or a top-level list of samples."
        }, 400)
 
    try:
        results = [_score_and_metrics(s) for s in samples]
    except Exception as e:
        return _ok({"error": f"Custom scoring failed: {e}"}, 500)
 
    return _ok(results)
```

**Exemple de message de récompense**

```
You are an expert RAG response evaluator specializing in faithfulness and relevance assessment.
Given: Context documents, a question, and response statements.
Goal: Evaluate both statement-level faithfulness and overall response relevance to the question.

Scoring rubric (start at 0.0, then add or subtract):

Core Components:

Faithfulness Assessment (0.6 max)
Per statement evaluation:
- Direct support in context: +0.2
- Accurate inference from context: +0.2
- No contradictions with context: +0.2
Deductions:
- Hallucination: -0.3
- Misrepresentation of context: -0.2
- Unsupported inference: -0.1

Question Relevance (0.4 max)
- Direct answer to question: +0.2
- Appropriate scope/detail: +0.1
- Proper context usage: +0.1
Deductions:
- Off-topic content: -0.2
- Implicit/meta responses: -0.2
- Missing key information: -0.1

Critical Flags:
A. Complete hallucination
B. Context misalignment
C. Question misinterpretation
D. Implicit-only responses

Additional Instructions:
- Evaluate each statement independently
- Check for direct textual support
- Verify logical inferences
- Assess answer completeness
- Flag any unsupported claims

Return EXACTLY this JSON (no extra text):
{
    "statements_evaluation": [
        {
            "statement": "<statement_text>",
            "verdict": <0 or 1>,
            "reason": "<detailed explanation>",
            "context_support": "<relevant context quote or 'None'>"
        }
    ],
    "overall_assessment": {
        "question_addressed": <0 or 1>,
        "reasoning": "<explanation>",
        "faithfulness_score": <0.0-1.0>,
        "relevance_score": <0.0-1.0>
    },
    "flags": ["<any critical issues>"]
}

## Current Evaluation Task

### Context
{{ ground_truth }}

### Question
{{ extra_info.question }}

### Model's Response
{{ model_output }}
```

# Note de publication
<a name="model-customize-release-note"></a>

**Les images de personnalisation du modèle d' SageMaker IA**

**Plan de support**
+ Versions majeures : 12 mois après la prochaine sortie majeure
+ Versions mineures : 6 mois après la prochaine sortie mineure
+ Versions du correctif : aucun support garanti (mise à niveau vers le dernier correctif)

Vous trouverez ci-dessous les notes de publication relatives aux applications de formation Base Deep Learning Containers for Amazon EKS (EKS) et SageMaker AI Training Jobs (SMTJ) :


****  

| Version | Type | Service | URL de l'image | 
| --- | --- | --- | --- | 
|  1.0.0  | CUDA | EKS |  `652744875666.dkr.ecr.amazonaws.com/hyperpod-model-customization:verl-eks-v1.0.0`  | 
|  1.0.0  | CUDA | SMTJ |  `652744875666.dkr.ecr.amazonaws.com/hyperpod-model-customization:verl-smtj-v1.0.0`  | 
|  1.0.0  | CUDA | SMJT |  `652744875666.dkr.ecr.amazonaws.com/hyperpod-model-customization:v1-v1.0.0`  | 
|  1.0.0  | CUDA | SMTJ |  `652744875666.dkr.ecr.amazonaws.com/hyperpod-model-customization:llama-90b-v1.0.0`  | 

**Régions AWS soutien**


****  

| Région | Code | Support SMTJ sans serveur | 
| --- | --- | --- | 
| Asie-Pacifique (Mumbai) | ap-south-1 | non | 
| Asie-Pacifique (Singapour) | ap-southeast-1 | non | 
| Asie-Pacifique (Sydney) | ap-southeast-2 | non | 
| Asie-Pacifique (Tokyo) | ap-northeast-1 | oui | 
| Europe (Francfort) | eu-central-1 | non | 
| Europe (Irlande) | eu-west-1 | oui | 
| Europe (Stockholm) | eu-north-1 | non | 
| Amérique du Sud (São Paulo) | sa-east-1 | non | 
| USA Est (Virginie du Nord) | us-east-1 | oui | 
| USA Est (Ohio) | us-east-2 | non | 
| USA Ouest (Californie du Nord) | us-west-1 | non | 
| USA Ouest (Oregon) | us-west-2 | oui | 