Spaces:
Running
Refactor CI/CD workflows and scripts for improved deployment and retraining processes
Browse files- Updated GitHub Actions workflows for AWS Lambda deployment and retraining to streamline processes and enhance readability.
- Added a new evaluation script to generate detailed evaluation reports including per-class recall and macro metrics.
- Enhanced the promotion gate logic to directly utilize new evaluation report fields, ensuring consistent decision-making based on model performance.
- Introduced a new admin UI for human labelers to facilitate audio review and labeling directly within the FastAPI application.
- Updated Makefile to include a new evaluation command for generating evaluation reports.
- Modified kernel metadata and training scripts to align with new evaluation and labeling processes.
- Improved error handling and validation in various scripts to ensure robustness against unexpected input.
- .github/workflows/deploy-aws-serverless .yml +10 -20
- .github/workflows/retrain.yml +59 -78
- Makefile +2 -0
- PIPELINE_README.md +0 -8
- app/api/admin_ui.py +71 -42
- data/telemetry.db +0 -0
- kaggle/kernel-metadata.json +3 -2
- kaggle/train_head_kernel.py +71 -61
- scripts/eval_report.py +34 -6
- scripts/promotion_gate.py +66 -103
|
@@ -1,5 +1,4 @@
|
|
| 1 |
name: Deploy to AWS Lambda
|
| 2 |
-
|
| 3 |
on:
|
| 4 |
repository_dispatch:
|
| 5 |
types: [deploy-triggered]
|
|
@@ -9,37 +8,31 @@ on:
|
|
| 9 |
- "app/**"
|
| 10 |
- "infra/aws-serverless/**"
|
| 11 |
workflow_dispatch: {}
|
| 12 |
-
|
| 13 |
permissions:
|
| 14 |
id-token: write
|
| 15 |
contents: read
|
| 16 |
-
|
| 17 |
env:
|
| 18 |
AWS_REGION: us-east-1
|
| 19 |
ECR_REPOSITORY: ser-inference
|
| 20 |
LAMBDA_FUNCTION: ser-inference
|
| 21 |
-
|
| 22 |
jobs:
|
| 23 |
deploy:
|
| 24 |
runs-on: ubuntu-latest
|
| 25 |
steps:
|
| 26 |
- uses: actions/checkout@v4
|
| 27 |
-
|
| 28 |
- name: Configure AWS credentials (OIDC)
|
| 29 |
uses: aws-actions/configure-aws-credentials@v4
|
| 30 |
with:
|
| 31 |
role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }}
|
| 32 |
aws-region: ${{ env.AWS_REGION }}
|
| 33 |
-
|
| 34 |
- name: Login to ECR
|
| 35 |
id: ecr
|
| 36 |
uses: aws-actions/amazon-ecr-login@v2
|
| 37 |
-
|
| 38 |
- name: Set up Docker Buildx
|
| 39 |
uses: docker/setup-buildx-action@v3
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
run: |
|
| 44 |
docker buildx build --platform linux/amd64 \
|
| 45 |
--provenance=false --sbom=false \
|
|
@@ -50,26 +43,23 @@ jobs:
|
|
| 50 |
-t ${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${{ github.sha }} \
|
| 51 |
-t ${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:latest \
|
| 52 |
--push .
|
| 53 |
-
|
| 54 |
- name: Update Lambda function code
|
| 55 |
run: |
|
| 56 |
aws lambda update-function-code \
|
| 57 |
--function-name ${{ env.LAMBDA_FUNCTION }} \
|
| 58 |
--image-uri ${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${{ github.sha }}
|
| 59 |
-
|
| 60 |
- name: Wait for update to finish
|
| 61 |
run: |
|
| 62 |
aws lambda wait function-updated \
|
| 63 |
--function-name ${{ env.LAMBDA_FUNCTION }}
|
| 64 |
-
|
| 65 |
- name: Post deploy confirmation
|
| 66 |
run: |
|
| 67 |
python -c "
|
| 68 |
-
import json, urllib.request, os
|
| 69 |
-
text = 'Deployed new champion to Lambda: ${{ github.sha }}'
|
| 70 |
-
body = json.dumps({'content': text, 'text': text}).encode()
|
| 71 |
-
req = urllib.request.Request(os.environ['ALERT_WEBHOOK_URL'], data=body, headers={'Content-Type': 'application/json'})
|
| 72 |
-
urllib.request.urlopen(req, timeout=5)
|
| 73 |
-
"
|
| 74 |
env:
|
| 75 |
-
ALERT_WEBHOOK_URL: ${{ secrets.ALERT_WEBHOOK_URL }}
|
|
|
|
| 1 |
name: Deploy to AWS Lambda
|
|
|
|
| 2 |
on:
|
| 3 |
repository_dispatch:
|
| 4 |
types: [deploy-triggered]
|
|
|
|
| 8 |
- "app/**"
|
| 9 |
- "infra/aws-serverless/**"
|
| 10 |
workflow_dispatch: {}
|
|
|
|
| 11 |
permissions:
|
| 12 |
id-token: write
|
| 13 |
contents: read
|
|
|
|
| 14 |
env:
|
| 15 |
AWS_REGION: us-east-1
|
| 16 |
ECR_REPOSITORY: ser-inference
|
| 17 |
LAMBDA_FUNCTION: ser-inference
|
|
|
|
| 18 |
jobs:
|
| 19 |
deploy:
|
| 20 |
runs-on: ubuntu-latest
|
| 21 |
steps:
|
| 22 |
- uses: actions/checkout@v4
|
|
|
|
| 23 |
- name: Configure AWS credentials (OIDC)
|
| 24 |
uses: aws-actions/configure-aws-credentials@v4
|
| 25 |
with:
|
| 26 |
role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }}
|
| 27 |
aws-region: ${{ env.AWS_REGION }}
|
|
|
|
| 28 |
- name: Login to ECR
|
| 29 |
id: ecr
|
| 30 |
uses: aws-actions/amazon-ecr-login@v2
|
|
|
|
| 31 |
- name: Set up Docker Buildx
|
| 32 |
uses: docker/setup-buildx-action@v3
|
| 33 |
+
# provenance/sbom OFF — Lambda rejects the multi-manifest index
|
| 34 |
+
# otherwise, same gotcha as Project 1
|
| 35 |
+
- name: Build and push
|
| 36 |
run: |
|
| 37 |
docker buildx build --platform linux/amd64 \
|
| 38 |
--provenance=false --sbom=false \
|
|
|
|
| 43 |
-t ${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${{ github.sha }} \
|
| 44 |
-t ${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:latest \
|
| 45 |
--push .
|
|
|
|
| 46 |
- name: Update Lambda function code
|
| 47 |
run: |
|
| 48 |
aws lambda update-function-code \
|
| 49 |
--function-name ${{ env.LAMBDA_FUNCTION }} \
|
| 50 |
--image-uri ${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${{ github.sha }}
|
|
|
|
| 51 |
- name: Wait for update to finish
|
| 52 |
run: |
|
| 53 |
aws lambda wait function-updated \
|
| 54 |
--function-name ${{ env.LAMBDA_FUNCTION }}
|
|
|
|
| 55 |
- name: Post deploy confirmation
|
| 56 |
run: |
|
| 57 |
python -c "
|
| 58 |
+
import json, urllib.request, os
|
| 59 |
+
text = 'Deployed new champion to Lambda: ${{ github.sha }}'
|
| 60 |
+
body = json.dumps({'content': text, 'text': text}).encode()
|
| 61 |
+
req = urllib.request.Request(os.environ['ALERT_WEBHOOK_URL'], data=body, headers={'Content-Type': 'application/json'})
|
| 62 |
+
urllib.request.urlopen(req, timeout=5)
|
| 63 |
+
"
|
| 64 |
env:
|
| 65 |
+
ALERT_WEBHOOK_URL: ${{ secrets.ALERT_WEBHOOK_URL }}
|
|
@@ -1,43 +1,35 @@
|
|
| 1 |
name: Retrain (Kaggle-triggered)
|
| 2 |
-
|
| 3 |
on:
|
| 4 |
repository_dispatch:
|
| 5 |
types: [retrain-triggered]
|
| 6 |
workflow_dispatch: {} # manual override, e.g. to force a run after adjusting policy thresholds
|
| 7 |
-
|
| 8 |
permissions:
|
| 9 |
id-token: write
|
| 10 |
contents: read
|
| 11 |
-
|
| 12 |
jobs:
|
| 13 |
retrain:
|
| 14 |
runs-on: ubuntu-latest
|
| 15 |
steps:
|
| 16 |
- uses: actions/checkout@v4
|
| 17 |
-
|
| 18 |
- name: Configure AWS credentials (OIDC)
|
| 19 |
uses: aws-actions/configure-aws-credentials@v4
|
| 20 |
with:
|
| 21 |
role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }}
|
| 22 |
aws-region: us-east-1
|
| 23 |
-
|
| 24 |
- uses: actions/setup-python@v5
|
| 25 |
with:
|
| 26 |
python-version: "3.11"
|
| 27 |
-
|
| 28 |
- run: pip install boto3 kaggle
|
| 29 |
-
|
| 30 |
- name: Read last training watermark
|
| 31 |
id: watermark
|
| 32 |
run: |
|
| 33 |
WATERMARK=$(python -c "
|
| 34 |
-
import boto3
|
| 35 |
-
t = boto3.resource('dynamodb').Table('ser-inference-retrain-state')
|
| 36 |
-
item = t.get_item(Key={'state_key': 'watermark'}).get('Item', {})
|
| 37 |
-
print(item.get('last_trained_at', '1970-01-01T00:00:00'))
|
| 38 |
-
")
|
| 39 |
echo "since=$WATERMARK" >> "$GITHUB_OUTPUT"
|
| 40 |
-
|
| 41 |
- name: Assemble Kaggle batch (push mode — no AWS creds on Kaggle)
|
| 42 |
run: |
|
| 43 |
python scripts/assemble_kaggle_batch.py \
|
|
@@ -50,7 +42,6 @@ print(item.get('last_trained_at', '1970-01-01T00:00:00'))
|
|
| 50 |
env:
|
| 51 |
KAGGLE_USERNAME: ${{ secrets.KAGGLE_USERNAME }}
|
| 52 |
KAGGLE_KEY: ${{ secrets.KAGGLE_KEY }}
|
| 53 |
-
|
| 54 |
- name: Trigger + poll Kaggle training kernel
|
| 55 |
run: |
|
| 56 |
python scripts/trigger_kaggle_kernel.py \
|
|
@@ -60,25 +51,23 @@ print(item.get('last_trained_at', '1970-01-01T00:00:00'))
|
|
| 60 |
env:
|
| 61 |
KAGGLE_USERNAME: ${{ secrets.KAGGLE_USERNAME }}
|
| 62 |
KAGGLE_KEY: ${{ secrets.KAGGLE_KEY }}
|
| 63 |
-
|
| 64 |
- name: Fetch current champion's eval report
|
| 65 |
run: |
|
| 66 |
# Pulled from the HF Hub revision currently baked into the
|
| 67 |
# deployed Lambda image, so the gate always diffs against
|
| 68 |
# what's ACTUALLY live, not a stale local copy.
|
| 69 |
python -c "
|
| 70 |
-
from huggingface_hub import hf_hub_download
|
| 71 |
-
import shutil
|
| 72 |
-
path = hf_hub_download(
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
)
|
| 77 |
-
shutil.copy(path, 'champion_eval_report.json')
|
| 78 |
-
"
|
| 79 |
env:
|
| 80 |
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 81 |
-
|
| 82 |
- name: Run promotion gate (macro F1, epsilon 0.01)
|
| 83 |
id: gate
|
| 84 |
continue-on-error: true # a reject is a valid, expected outcome — don't fail the job
|
|
@@ -91,42 +80,39 @@ shutil.copy(path, 'champion_eval_report.json')
|
|
| 91 |
--recall-key recall.per_class \
|
| 92 |
--per-class-tolerance 0.02 \
|
| 93 |
--out decision.json
|
| 94 |
-
|
| 95 |
- name: Post decision to alert webhook
|
| 96 |
run: |
|
| 97 |
python -c "
|
| 98 |
-
import json, urllib.request, os
|
| 99 |
-
decision = json.load(open('decision.json'))
|
| 100 |
-
text = f\"Retrain decision: **{decision['decision'].upper()}** — \" + '; '.join(decision['reasons'])
|
| 101 |
-
body = json.dumps({'content': text, 'text': text}).encode()
|
| 102 |
-
req = urllib.request.Request(os.environ['ALERT_WEBHOOK_URL'], data=body, headers={'Content-Type': 'application/json'})
|
| 103 |
-
urllib.request.urlopen(req, timeout=5)
|
| 104 |
-
"
|
| 105 |
env:
|
| 106 |
ALERT_WEBHOOK_URL: ${{ secrets.ALERT_WEBHOOK_URL }}
|
| 107 |
-
|
| 108 |
- name: Promote — push new revision to HF Hub
|
| 109 |
if: steps.gate.outcome == 'success'
|
| 110 |
run: |
|
| 111 |
python -c "
|
| 112 |
-
from huggingface_hub import HfApi
|
| 113 |
-
api = HfApi()
|
| 114 |
-
api.upload_file(
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
)
|
| 120 |
-
api.upload_file(
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
)
|
| 126 |
-
"
|
| 127 |
env:
|
| 128 |
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 129 |
-
|
| 130 |
- name: Update embeddings cache dataset on Kaggle
|
| 131 |
if: always()
|
| 132 |
run: |
|
|
@@ -135,39 +121,34 @@ api.upload_file(
|
|
| 135 |
env:
|
| 136 |
KAGGLE_USERNAME: ${{ secrets.KAGGLE_USERNAME }}
|
| 137 |
KAGGLE_KEY: ${{ secrets.KAGGLE_KEY }}
|
| 138 |
-
|
| 139 |
- name: Update watermark + mark items deployed
|
| 140 |
if: always()
|
| 141 |
run: |
|
| 142 |
python -c "
|
| 143 |
-
import json, boto3
|
| 144 |
-
from datetime import datetime, timezone
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
ExpressionAttributeValues={':d': 'deployed'},
|
| 166 |
-
)
|
| 167 |
-
"
|
| 168 |
-
|
| 169 |
- name: Trigger deploy workflow
|
| 170 |
if: steps.gate.outcome == 'success'
|
| 171 |
uses: peter-evans/repository-dispatch@v3
|
| 172 |
with:
|
| 173 |
-
event-type: deploy-triggered
|
|
|
|
| 1 |
name: Retrain (Kaggle-triggered)
|
|
|
|
| 2 |
on:
|
| 3 |
repository_dispatch:
|
| 4 |
types: [retrain-triggered]
|
| 5 |
workflow_dispatch: {} # manual override, e.g. to force a run after adjusting policy thresholds
|
|
|
|
| 6 |
permissions:
|
| 7 |
id-token: write
|
| 8 |
contents: read
|
|
|
|
| 9 |
jobs:
|
| 10 |
retrain:
|
| 11 |
runs-on: ubuntu-latest
|
| 12 |
steps:
|
| 13 |
- uses: actions/checkout@v4
|
|
|
|
| 14 |
- name: Configure AWS credentials (OIDC)
|
| 15 |
uses: aws-actions/configure-aws-credentials@v4
|
| 16 |
with:
|
| 17 |
role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }}
|
| 18 |
aws-region: us-east-1
|
|
|
|
| 19 |
- uses: actions/setup-python@v5
|
| 20 |
with:
|
| 21 |
python-version: "3.11"
|
|
|
|
| 22 |
- run: pip install boto3 kaggle
|
|
|
|
| 23 |
- name: Read last training watermark
|
| 24 |
id: watermark
|
| 25 |
run: |
|
| 26 |
WATERMARK=$(python -c "
|
| 27 |
+
import boto3
|
| 28 |
+
t = boto3.resource('dynamodb').Table('ser-inference-retrain-state')
|
| 29 |
+
item = t.get_item(Key={'state_key': 'watermark'}).get('Item', {})
|
| 30 |
+
print(item.get('last_trained_at', '1970-01-01T00:00:00'))
|
| 31 |
+
")
|
| 32 |
echo "since=$WATERMARK" >> "$GITHUB_OUTPUT"
|
|
|
|
| 33 |
- name: Assemble Kaggle batch (push mode — no AWS creds on Kaggle)
|
| 34 |
run: |
|
| 35 |
python scripts/assemble_kaggle_batch.py \
|
|
|
|
| 42 |
env:
|
| 43 |
KAGGLE_USERNAME: ${{ secrets.KAGGLE_USERNAME }}
|
| 44 |
KAGGLE_KEY: ${{ secrets.KAGGLE_KEY }}
|
|
|
|
| 45 |
- name: Trigger + poll Kaggle training kernel
|
| 46 |
run: |
|
| 47 |
python scripts/trigger_kaggle_kernel.py \
|
|
|
|
| 51 |
env:
|
| 52 |
KAGGLE_USERNAME: ${{ secrets.KAGGLE_USERNAME }}
|
| 53 |
KAGGLE_KEY: ${{ secrets.KAGGLE_KEY }}
|
|
|
|
| 54 |
- name: Fetch current champion's eval report
|
| 55 |
run: |
|
| 56 |
# Pulled from the HF Hub revision currently baked into the
|
| 57 |
# deployed Lambda image, so the gate always diffs against
|
| 58 |
# what's ACTUALLY live, not a stale local copy.
|
| 59 |
python -c "
|
| 60 |
+
from huggingface_hub import hf_hub_download
|
| 61 |
+
import shutil
|
| 62 |
+
path = hf_hub_download(
|
| 63 |
+
repo_id='${{ vars.HF_MODEL_REPO }}',
|
| 64 |
+
filename='metrics.json',
|
| 65 |
+
revision='${{ vars.HF_CHAMPION_REVISION }}',
|
| 66 |
+
)
|
| 67 |
+
shutil.copy(path, 'champion_eval_report.json')
|
| 68 |
+
"
|
| 69 |
env:
|
| 70 |
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
|
|
|
| 71 |
- name: Run promotion gate (macro F1, epsilon 0.01)
|
| 72 |
id: gate
|
| 73 |
continue-on-error: true # a reject is a valid, expected outcome — don't fail the job
|
|
|
|
| 80 |
--recall-key recall.per_class \
|
| 81 |
--per-class-tolerance 0.02 \
|
| 82 |
--out decision.json
|
|
|
|
| 83 |
- name: Post decision to alert webhook
|
| 84 |
run: |
|
| 85 |
python -c "
|
| 86 |
+
import json, urllib.request, os
|
| 87 |
+
decision = json.load(open('decision.json'))
|
| 88 |
+
text = f\"Retrain decision: **{decision['decision'].upper()}** — \" + '; '.join(decision['reasons'])
|
| 89 |
+
body = json.dumps({'content': text, 'text': text}).encode()
|
| 90 |
+
req = urllib.request.Request(os.environ['ALERT_WEBHOOK_URL'], data=body, headers={'Content-Type': 'application/json'})
|
| 91 |
+
urllib.request.urlopen(req, timeout=5)
|
| 92 |
+
"
|
| 93 |
env:
|
| 94 |
ALERT_WEBHOOK_URL: ${{ secrets.ALERT_WEBHOOK_URL }}
|
|
|
|
| 95 |
- name: Promote — push new revision to HF Hub
|
| 96 |
if: steps.gate.outcome == 'success'
|
| 97 |
run: |
|
| 98 |
python -c "
|
| 99 |
+
from huggingface_hub import HfApi
|
| 100 |
+
api = HfApi()
|
| 101 |
+
api.upload_file(
|
| 102 |
+
path_or_fileobj='/tmp/kaggle-output/challenger_head.pt',
|
| 103 |
+
path_in_repo='head.pt',
|
| 104 |
+
repo_id='${{ vars.HF_MODEL_REPO }}',
|
| 105 |
+
commit_message='promoted challenger — see decision.json',
|
| 106 |
+
)
|
| 107 |
+
api.upload_file(
|
| 108 |
+
path_or_fileobj='/tmp/kaggle-output/challenger_eval_report.json',
|
| 109 |
+
path_in_repo='metrics.json',
|
| 110 |
+
repo_id='${{ vars.HF_MODEL_REPO }}',
|
| 111 |
+
commit_message='challenger metrics',
|
| 112 |
+
)
|
| 113 |
+
"
|
| 114 |
env:
|
| 115 |
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
|
|
|
| 116 |
- name: Update embeddings cache dataset on Kaggle
|
| 117 |
if: always()
|
| 118 |
run: |
|
|
|
|
| 121 |
env:
|
| 122 |
KAGGLE_USERNAME: ${{ secrets.KAGGLE_USERNAME }}
|
| 123 |
KAGGLE_KEY: ${{ secrets.KAGGLE_KEY }}
|
|
|
|
| 124 |
- name: Update watermark + mark items deployed
|
| 125 |
if: always()
|
| 126 |
run: |
|
| 127 |
python -c "
|
| 128 |
+
import json, boto3
|
| 129 |
+
from datetime import datetime, timezone
|
| 130 |
+
decision = json.load(open('decision.json'))
|
| 131 |
+
promoted = decision['decision'] == 'promote'
|
| 132 |
+
dynamodb = boto3.resource('dynamodb')
|
| 133 |
+
state = dynamodb.Table('ser-inference-retrain-state')
|
| 134 |
+
state.put_item(Item={
|
| 135 |
+
'state_key': 'watermark',
|
| 136 |
+
'last_trained_at': datetime.now(timezone.utc).isoformat(),
|
| 137 |
+
'last_decision': decision['decision'],
|
| 138 |
+
})
|
| 139 |
+
if promoted:
|
| 140 |
+
manifest = json.load(open('batch_manifest.json'))
|
| 141 |
+
queue = dynamodb.Table('ser-inference-review-queue')
|
| 142 |
+
for rid in manifest['request_ids']:
|
| 143 |
+
queue.update_item(
|
| 144 |
+
Key={'request_id': rid},
|
| 145 |
+
UpdateExpression='SET #s = :d',
|
| 146 |
+
ExpressionAttributeNames={'#s': 'status'},
|
| 147 |
+
ExpressionAttributeValues={':d': 'deployed'},
|
| 148 |
+
)
|
| 149 |
+
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
- name: Trigger deploy workflow
|
| 151 |
if: steps.gate.outcome == 'success'
|
| 152 |
uses: peter-evans/repository-dispatch@v3
|
| 153 |
with:
|
| 154 |
+
event-type: deploy-triggered
|
|
@@ -17,3 +17,5 @@ latency:
|
|
| 17 |
|
| 18 |
calibrate:
|
| 19 |
python scripts/calibration_fit.py --predictions data/val_predictions.csv --method isotonic
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
calibrate:
|
| 19 |
python scripts/calibration_fit.py --predictions data/val_predictions.csv --method isotonic
|
| 20 |
+
evaluate:
|
| 21 |
+
python scripts/eval_report.py --predictions data/val_predictions.csv --out data/eval_report.json
|
|
@@ -138,12 +138,4 @@ pytest tests/ -v
|
|
| 138 |
| 3.5 CI/CD | `.github/workflows/ci-eval-gate.yml` |
|
| 139 |
|
| 140 |
|
| 141 |
-
---
|
| 142 |
-
title: Ser Inference
|
| 143 |
-
emoji: 🚀
|
| 144 |
-
colorFrom: pink
|
| 145 |
-
colorTo: green
|
| 146 |
-
sdk: docker
|
| 147 |
-
pinned: false
|
| 148 |
-
---
|
| 149 |
|
|
|
|
| 138 |
| 3.5 CI/CD | `.github/workflows/ci-eval-gate.yml` |
|
| 139 |
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
|
@@ -1,67 +1,93 @@
|
|
| 1 |
"""
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
-
|
| 5 |
-
from urllib.parse import quote
|
| 6 |
|
| 7 |
import boto3
|
| 8 |
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
| 9 |
-
from fastapi.responses import HTMLResponse
|
| 10 |
|
| 11 |
router = APIRouter(prefix="/admin", tags=["admin"])
|
| 12 |
|
|
|
|
|
|
|
|
|
|
| 13 |
_secret_cache: str | None = None
|
| 14 |
|
| 15 |
|
| 16 |
-
def _get_admin_secret(
|
| 17 |
global _secret_cache
|
| 18 |
if _secret_cache is None:
|
| 19 |
-
param_name =
|
| 20 |
-
|
| 21 |
-
raise HTTPException(status_code=404, detail="admin UI is not configured")
|
| 22 |
-
resp = boto3.client("ssm").get_parameter(Name=param_name, WithDecryption=True)
|
| 23 |
_secret_cache = resp["Parameter"]["Value"]
|
| 24 |
return _secret_cache
|
| 25 |
|
| 26 |
|
| 27 |
-
def _require_auth(
|
| 28 |
-
if token != _get_admin_secret(
|
| 29 |
raise HTTPException(status_code=403, detail="bad token")
|
| 30 |
|
| 31 |
|
| 32 |
@router.get("/label", response_class=HTMLResponse)
|
| 33 |
def label_page(request: Request, _=Depends(_require_auth), token: str = Query(...)):
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
quoted_token = quote(token, safe="")
|
| 42 |
|
| 43 |
rows = []
|
| 44 |
for item in items:
|
| 45 |
-
audio_url =
|
| 46 |
"get_object",
|
| 47 |
Params={"Bucket": bucket, "Key": item["s3_audio_key"]},
|
| 48 |
ExpiresIn=3600,
|
| 49 |
)
|
| 50 |
-
prediction = item.get("prediction", {})
|
| 51 |
-
label = escape(str(prediction.get("label", "?")))
|
| 52 |
-
confidence = escape(str(item.get("confidence", "?")))
|
| 53 |
-
request_id = escape(str(item["request_id"]))
|
| 54 |
rows.append(f"""
|
| 55 |
-
<div class="item" data-request-id="{request_id}">
|
| 56 |
-
<p><b>{request_id}</b> model said
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
| 60 |
<select name="label">
|
| 61 |
-
<option>
|
| 62 |
-
<option>
|
| 63 |
-
<option>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
</select>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
<button type="submit">Submit label</button>
|
| 66 |
</form>
|
| 67 |
</div>
|
|
@@ -69,12 +95,8 @@ def label_page(request: Request, _=Depends(_require_auth), token: str = Query(..
|
|
| 69 |
|
| 70 |
html = f"""
|
| 71 |
<html><head><title>SER review queue</title>
|
| 72 |
-
<style>
|
| 73 |
-
|
| 74 |
-
.item{{border:1px solid #ccc;padding:1rem;margin-bottom:1rem;border-radius:8px}}
|
| 75 |
-
audio{{display:block;width:100%;margin:.75rem 0}}
|
| 76 |
-
button,select{{font:inherit}}
|
| 77 |
-
</style>
|
| 78 |
</head><body>
|
| 79 |
<h1>Pending review ({len(items)})</h1>
|
| 80 |
{''.join(rows) if rows else '<p>Nothing pending.</p>'}
|
|
@@ -84,10 +106,17 @@ def label_page(request: Request, _=Depends(_require_auth), token: str = Query(..
|
|
| 84 |
|
| 85 |
|
| 86 |
@router.post("/label")
|
| 87 |
-
async def submit_label(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
form = await request.form()
|
| 89 |
-
request_id =
|
| 90 |
-
label =
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
|
| 93 |
-
return RedirectResponse(url=f"/admin/label?token={
|
|
|
|
| 1 |
"""
|
| 2 |
+
app/api/admin_ui.py
|
| 3 |
+
|
| 4 |
+
Adds one server-rendered HTML page to the existing FastAPI app for the
|
| 5 |
+
solo human labeler: list pending review-queue items, play the audio via
|
| 6 |
+
a presigned S3 URL, submit a label. No separate frontend build or host
|
| 7 |
+
— it's mounted into the same app that already serves /predict.
|
| 8 |
+
|
| 9 |
+
Wire this in by including its router in main.py:
|
| 10 |
+
|
| 11 |
+
from app.api.admin_ui import router as admin_ui_router
|
| 12 |
+
app.include_router(admin_ui_router)
|
| 13 |
+
|
| 14 |
+
Protected by a single shared secret (checked via a query param or
|
| 15 |
+
cookie) pulled from SSM at cold start — fine for a one-person labeling
|
| 16 |
+
workflow, not meant to scale past that.
|
| 17 |
"""
|
| 18 |
+
import os
|
|
|
|
| 19 |
|
| 20 |
import boto3
|
| 21 |
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
| 22 |
+
from fastapi.responses import HTMLResponse
|
| 23 |
|
| 24 |
router = APIRouter(prefix="/admin", tags=["admin"])
|
| 25 |
|
| 26 |
+
_ssm = boto3.client("ssm")
|
| 27 |
+
_s3 = boto3.client("s3")
|
| 28 |
+
|
| 29 |
_secret_cache: str | None = None
|
| 30 |
|
| 31 |
|
| 32 |
+
def _get_admin_secret() -> str:
|
| 33 |
global _secret_cache
|
| 34 |
if _secret_cache is None:
|
| 35 |
+
param_name = os.environ["ADMIN_UI_SECRET_PARAM"]
|
| 36 |
+
resp = _ssm.get_parameter(Name=param_name, WithDecryption=True)
|
|
|
|
|
|
|
| 37 |
_secret_cache = resp["Parameter"]["Value"]
|
| 38 |
return _secret_cache
|
| 39 |
|
| 40 |
|
| 41 |
+
def _require_auth(token: str = Query(...)):
|
| 42 |
+
if token != _get_admin_secret():
|
| 43 |
raise HTTPException(status_code=403, detail="bad token")
|
| 44 |
|
| 45 |
|
| 46 |
@router.get("/label", response_class=HTMLResponse)
|
| 47 |
def label_page(request: Request, _=Depends(_require_auth), token: str = Query(...)):
|
| 48 |
+
# NOTE: this calls into the existing review-queue backend's
|
| 49 |
+
# list_pending() — import path below assumes the factory function
|
| 50 |
+
# from config_additions.py's wiring. Adjust to match however
|
| 51 |
+
# review_queue.py actually exposes the active backend instance.
|
| 52 |
+
from app.logging_pipeline.review_queue import get_review_queue_backend
|
| 53 |
|
| 54 |
+
backend = get_review_queue_backend()
|
| 55 |
+
items = backend.list_pending(limit=20)
|
| 56 |
+
bucket = os.environ["AUDIO_BUCKET"]
|
|
|
|
| 57 |
|
| 58 |
rows = []
|
| 59 |
for item in items:
|
| 60 |
+
audio_url = _s3.generate_presigned_url(
|
| 61 |
"get_object",
|
| 62 |
Params={"Bucket": bucket, "Key": item["s3_audio_key"]},
|
| 63 |
ExpiresIn=3600,
|
| 64 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
rows.append(f"""
|
| 66 |
+
<div class="item" data-request-id="{item['request_id']}">
|
| 67 |
+
<p><b>{item['request_id']}</b> — model said
|
| 68 |
+
<code>{item['prediction'].get('label', '?')}</code>
|
| 69 |
+
(confidence {item.get('confidence', '?')})</p>
|
| 70 |
+
<audio controls src="{audio_url}"></audio>
|
| 71 |
+
<form method="post" action="/admin/label?token={token}">
|
| 72 |
+
<input type="hidden" name="request_id" value="{item['request_id']}">
|
| 73 |
<select name="label">
|
| 74 |
+
<option value="angry">Angry</option>
|
| 75 |
+
<option value="calm">Calm</option>
|
| 76 |
+
<option value="disgust">Disgust</option>
|
| 77 |
+
<option value="fearful">Fearful</option>
|
| 78 |
+
<option value="happy">Happy</option>
|
| 79 |
+
<option value="neutral" selected>Neutral</option>
|
| 80 |
+
<option value="sad">Sad</option>
|
| 81 |
+
<option value="surprised">Surprised</option>
|
| 82 |
</select>
|
| 83 |
+
<!-- option VALUES must match scripts/eval_report.py's
|
| 84 |
+
IDX_TO_EMOTION values exactly (lowercase, includes
|
| 85 |
+
"calm", "fearful"/"surprised" not "fear"/"surprise").
|
| 86 |
+
kaggle/train_head_kernel.py's encode_label() will raise
|
| 87 |
+
loudly on anything else, rather than silently corrupt
|
| 88 |
+
a training batch — but better to never submit a bad
|
| 89 |
+
value in the first place. -->
|
| 90 |
+
|
| 91 |
<button type="submit">Submit label</button>
|
| 92 |
</form>
|
| 93 |
</div>
|
|
|
|
| 95 |
|
| 96 |
html = f"""
|
| 97 |
<html><head><title>SER review queue</title>
|
| 98 |
+
<style>body{{font-family:sans-serif;max-width:600px;margin:2rem auto}}
|
| 99 |
+
.item{{border:1px solid #ccc;padding:1rem;margin-bottom:1rem;border-radius:8px}}</style>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
</head><body>
|
| 101 |
<h1>Pending review ({len(items)})</h1>
|
| 102 |
{''.join(rows) if rows else '<p>Nothing pending.</p>'}
|
|
|
|
| 106 |
|
| 107 |
|
| 108 |
@router.post("/label")
|
| 109 |
+
async def submit_label(
|
| 110 |
+
request: Request, token: str = Query(...), _=Depends(_require_auth)
|
| 111 |
+
):
|
| 112 |
+
from app.logging_pipeline.review_queue import get_review_queue_backend
|
| 113 |
+
|
| 114 |
form = await request.form()
|
| 115 |
+
request_id = form["request_id"]
|
| 116 |
+
label = form["label"]
|
| 117 |
+
|
| 118 |
+
backend = get_review_queue_backend()
|
| 119 |
+
backend.mark_labeled(request_id, label)
|
| 120 |
|
| 121 |
+
from fastapi.responses import RedirectResponse
|
| 122 |
+
return RedirectResponse(url=f"/admin/label?token={token}", status_code=303)
|
|
Binary files a/data/telemetry.db and b/data/telemetry.db differ
|
|
|
|
@@ -10,8 +10,9 @@
|
|
| 10 |
"dataset_sources": [
|
| 11 |
"your-username/ser-retrain-batch",
|
| 12 |
"your-username/ser-eval-set-pinned",
|
| 13 |
-
"your-username/ser-embeddings-cache"
|
|
|
|
| 14 |
],
|
| 15 |
"kernel_sources": [],
|
| 16 |
"competition_sources": []
|
| 17 |
-
}
|
|
|
|
| 10 |
"dataset_sources": [
|
| 11 |
"your-username/ser-retrain-batch",
|
| 12 |
"your-username/ser-eval-set-pinned",
|
| 13 |
+
"your-username/ser-embeddings-cache",
|
| 14 |
+
"your-username/ser-inference-src"
|
| 15 |
],
|
| 16 |
"kernel_sources": [],
|
| 17 |
"competition_sources": []
|
| 18 |
+
}
|
|
@@ -4,35 +4,20 @@ kaggle/train_head_kernel.py
|
|
| 4 |
Runs ON KAGGLE (GPU, no internet — see kernel-metadata.json). Consumes
|
| 5 |
three pinned dataset versions attached to the kernel:
|
| 6 |
- ser-retrain-batch: this run's new labeled audio + manifest.csv
|
| 7 |
-
(
|
|
|
|
| 8 |
- ser-eval-set-pinned: the FIXED held-out set — never changes
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
embedding extraction forward pass over the full accumulated dataset is
|
| 19 |
-
faster there than on a GH Actions CPU runner, not because backprop
|
| 20 |
-
through WavLM is happening.
|
| 21 |
-
|
| 22 |
-
Outputs (left in /kaggle/working/, which `kaggle kernels output` pulls
|
| 23 |
-
back to GH Actions):
|
| 24 |
-
- challenger_head.pt new MLP head weights
|
| 25 |
-
- challenger_eval_report.json eval_report.py's output, scored
|
| 26 |
-
against ser-eval-set-pinned
|
| 27 |
-
- updated_embeddings_cache.npz merged cache for next run's reuse
|
| 28 |
-
|
| 29 |
-
NOTE: I have not seen your actual classifier.py / eval_report.py
|
| 30 |
-
source, so the WavLM loading, MLPClassifier construction, and
|
| 31 |
-
eval_report.py invocation below are written against the interfaces
|
| 32 |
-
implied by PIPELINE_README.md's descriptions. Check these against your
|
| 33 |
-
real `app/model/classifier.py` and `scripts/eval_report.py` before
|
| 34 |
-
trusting kernel output.
|
| 35 |
"""
|
|
|
|
| 36 |
import json
|
| 37 |
import subprocess
|
| 38 |
import sys
|
|
@@ -42,7 +27,14 @@ import numpy as np
|
|
| 42 |
import torch
|
| 43 |
import torchaudio
|
| 44 |
|
| 45 |
-
sys.path.insert(0, "/kaggle/input/ser-inference-src") #
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
BATCH_DIR = Path("/kaggle/input/ser-retrain-batch")
|
| 48 |
EVAL_DIR = Path("/kaggle/input/ser-eval-set-pinned")
|
|
@@ -54,9 +46,6 @@ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
| 54 |
|
| 55 |
def load_frozen_wavlm():
|
| 56 |
from transformers import WavLMModel
|
| 57 |
-
# Pin the exact revision that matches the currently-deployed head —
|
| 58 |
-
# a mismatched backbone silently produces a different embedding
|
| 59 |
-
# space and the head's weights become meaningless.
|
| 60 |
model = WavLMModel.from_pretrained(
|
| 61 |
"microsoft/wavlm-large", revision="<pin-exact-revision-here>"
|
| 62 |
)
|
|
@@ -66,86 +55,107 @@ def load_frozen_wavlm():
|
|
| 66 |
return model
|
| 67 |
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
def extract_embeddings(wavlm, manifest_rows, audio_dir):
|
| 70 |
-
embeddings,
|
| 71 |
with torch.no_grad():
|
| 72 |
for row in manifest_rows:
|
| 73 |
wav, sr = torchaudio.load(audio_dir / row["filename"])
|
| 74 |
if sr != 16000:
|
| 75 |
wav = torchaudio.functional.resample(wav, sr, 16000)
|
| 76 |
wav = wav.to(DEVICE)
|
| 77 |
-
out = wavlm(wav).last_hidden_state.mean(dim=1)
|
| 78 |
embeddings.append(out.squeeze(0).cpu().numpy())
|
| 79 |
-
|
| 80 |
request_ids.append(row["request_id"])
|
| 81 |
-
return np.stack(embeddings),
|
| 82 |
|
| 83 |
|
| 84 |
-
def
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
|
|
|
|
|
|
| 87 |
wavlm = load_frozen_wavlm()
|
| 88 |
|
| 89 |
-
# --- new batch ---
|
| 90 |
manifest_rows = list(csv.DictReader(open(BATCH_DIR / "manifest.csv")))
|
| 91 |
-
new_embeddings,
|
| 92 |
wavlm, manifest_rows, BATCH_DIR / "audio"
|
| 93 |
)
|
| 94 |
|
| 95 |
-
# --- merge with cached embeddings from prior runs ---
|
| 96 |
cache_path = CACHE_DIR / "embeddings_cache.npz"
|
| 97 |
if cache_path.exists():
|
| 98 |
cache = np.load(cache_path, allow_pickle=True)
|
| 99 |
all_embeddings = np.concatenate([cache["embeddings"], new_embeddings])
|
| 100 |
-
|
| 101 |
else:
|
| 102 |
-
all_embeddings,
|
| 103 |
|
| 104 |
np.savez(
|
| 105 |
OUT_DIR / "updated_embeddings_cache.npz",
|
| 106 |
embeddings=all_embeddings,
|
| 107 |
-
|
| 108 |
)
|
| 109 |
|
| 110 |
# --- retrain the MLP head ---
|
| 111 |
# ADJUST to match app/model/classifier.py's actual MLPClassifier
|
| 112 |
-
# definition
|
| 113 |
-
# brevity; your real head may be a torch.nn.Module trained with an
|
| 114 |
-
# explicit loop instead.
|
| 115 |
from sklearn.neural_network import MLPClassifier
|
| 116 |
-
from sklearn.preprocessing import LabelEncoder
|
| 117 |
|
| 118 |
-
le = LabelEncoder()
|
| 119 |
-
y = le.fit_transform(all_labels)
|
| 120 |
head = MLPClassifier(hidden_layer_sizes=(128,), max_iter=500)
|
| 121 |
-
head.fit(all_embeddings,
|
| 122 |
|
| 123 |
import joblib
|
| 124 |
-
joblib.dump({"model": head, "
|
| 125 |
|
| 126 |
# --- evaluate against the PINNED held-out set ---
|
| 127 |
eval_manifest = list(csv.DictReader(open(EVAL_DIR / "manifest.csv")))
|
| 128 |
-
eval_embeddings,
|
| 129 |
wavlm, eval_manifest, EVAL_DIR / "audio"
|
| 130 |
)
|
| 131 |
-
|
| 132 |
-
|
|
|
|
| 133 |
|
| 134 |
predictions_csv = OUT_DIR / "val_predictions.csv"
|
| 135 |
with open(predictions_csv, "w", newline="") as f:
|
| 136 |
writer = csv.writer(f)
|
| 137 |
-
writer.writerow(["request_id", "true_label"
|
| 138 |
-
for rid,
|
| 139 |
-
writer.writerow([rid,
|
| 140 |
|
| 141 |
-
# Reuse eval_report.py UNMODIFIED
|
| 142 |
-
#
|
| 143 |
-
#
|
| 144 |
subprocess.run(
|
| 145 |
[
|
| 146 |
"python", "/kaggle/input/ser-inference-src/scripts/eval_report.py",
|
| 147 |
"--predictions", str(predictions_csv),
|
| 148 |
"--out", str(OUT_DIR / "challenger_eval_report.json"),
|
|
|
|
| 149 |
],
|
| 150 |
check=True,
|
| 151 |
)
|
|
@@ -156,4 +166,4 @@ def main():
|
|
| 156 |
|
| 157 |
|
| 158 |
if __name__ == "__main__":
|
| 159 |
-
main()
|
|
|
|
| 4 |
Runs ON KAGGLE (GPU, no internet — see kernel-metadata.json). Consumes
|
| 5 |
three pinned dataset versions attached to the kernel:
|
| 6 |
- ser-retrain-batch: this run's new labeled audio + manifest.csv
|
| 7 |
+
(filename, label, request_id — label is a
|
| 8 |
+
canonical lowercase emotion string)
|
| 9 |
- ser-eval-set-pinned: the FIXED held-out set — never changes
|
| 10 |
+
- ser-embeddings-cache: accumulated WavLM embeddings from prior runs
|
| 11 |
+
|
| 12 |
+
CANONICAL LABEL SCHEME — must match scripts/eval_report.py's
|
| 13 |
+
IDX_TO_EMOTION EXACTLY. Duplicated here (not imported) because this
|
| 14 |
+
runs in the Kaggle sandbox, a different environment than the
|
| 15 |
+
GH-Actions-run eval_report.py — if you later attach the repo itself as
|
| 16 |
+
a kernel dataset_source and import app.emotion_labels or similar from
|
| 17 |
+
both places instead, update this comment and remove the duplication.
|
| 18 |
+
If you change one of these dicts, you MUST change the other.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
"""
|
| 20 |
+
import csv
|
| 21 |
import json
|
| 22 |
import subprocess
|
| 23 |
import sys
|
|
|
|
| 27 |
import torch
|
| 28 |
import torchaudio
|
| 29 |
|
| 30 |
+
sys.path.insert(0, "/kaggle/input/ser-inference-src") # only used for eval_report.py subprocess call below
|
| 31 |
+
|
| 32 |
+
EMOTION_TO_IDX = {
|
| 33 |
+
"angry": 0, "calm": 1, "disgust": 2, "fearful": 3,
|
| 34 |
+
"happy": 4, "neutral": 5, "sad": 6, "surprised": 7,
|
| 35 |
+
}
|
| 36 |
+
IDX_TO_EMOTION = {v: k for k, v in EMOTION_TO_IDX.items()}
|
| 37 |
+
NUM_CLASSES = 8
|
| 38 |
|
| 39 |
BATCH_DIR = Path("/kaggle/input/ser-retrain-batch")
|
| 40 |
EVAL_DIR = Path("/kaggle/input/ser-eval-set-pinned")
|
|
|
|
| 46 |
|
| 47 |
def load_frozen_wavlm():
|
| 48 |
from transformers import WavLMModel
|
|
|
|
|
|
|
|
|
|
| 49 |
model = WavLMModel.from_pretrained(
|
| 50 |
"microsoft/wavlm-large", revision="<pin-exact-revision-here>"
|
| 51 |
)
|
|
|
|
| 55 |
return model
|
| 56 |
|
| 57 |
|
| 58 |
+
def encode_label(label_str: str) -> int:
|
| 59 |
+
"""Raises loudly on an unrecognized label string, rather than
|
| 60 |
+
silently corrupting the training set — a typo in the admin UI's
|
| 61 |
+
submitted label (or a future label taxonomy change) should fail
|
| 62 |
+
the kernel run, not train on garbage."""
|
| 63 |
+
key = label_str.strip().lower()
|
| 64 |
+
if key not in EMOTION_TO_IDX:
|
| 65 |
+
raise ValueError(
|
| 66 |
+
f"Unrecognized label '{label_str}' — must be one of "
|
| 67 |
+
f"{sorted(EMOTION_TO_IDX)}. Check the admin UI's submitted "
|
| 68 |
+
f"value and scripts/eval_report.py's IDX_TO_EMOTION for drift."
|
| 69 |
+
)
|
| 70 |
+
return EMOTION_TO_IDX[key]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
def extract_embeddings(wavlm, manifest_rows, audio_dir):
|
| 74 |
+
embeddings, label_indices, request_ids = [], [], []
|
| 75 |
with torch.no_grad():
|
| 76 |
for row in manifest_rows:
|
| 77 |
wav, sr = torchaudio.load(audio_dir / row["filename"])
|
| 78 |
if sr != 16000:
|
| 79 |
wav = torchaudio.functional.resample(wav, sr, 16000)
|
| 80 |
wav = wav.to(DEVICE)
|
| 81 |
+
out = wavlm(wav).last_hidden_state.mean(dim=1)
|
| 82 |
embeddings.append(out.squeeze(0).cpu().numpy())
|
| 83 |
+
label_indices.append(encode_label(row["label"]))
|
| 84 |
request_ids.append(row["request_id"])
|
| 85 |
+
return np.stack(embeddings), np.array(label_indices), request_ids
|
| 86 |
|
| 87 |
|
| 88 |
+
def expand_proba_to_full_width(proba: np.ndarray, classes_seen: np.ndarray) -> np.ndarray:
|
| 89 |
+
"""sklearn's predict_proba only returns columns for classes present
|
| 90 |
+
at fit time. If the training batch didn't contain all 8 emotions,
|
| 91 |
+
proba.shape[1] < 8 and the columns won't align with prob_0..prob_7.
|
| 92 |
+
This pads with zero-probability columns for any class absent from
|
| 93 |
+
training, so the output CSV always has exactly 8 prob columns in
|
| 94 |
+
the canonical index order eval_report.py expects."""
|
| 95 |
+
full = np.zeros((proba.shape[0], NUM_CLASSES), dtype=proba.dtype)
|
| 96 |
+
for col_idx, class_label in enumerate(classes_seen):
|
| 97 |
+
full[:, int(class_label)] = proba[:, col_idx]
|
| 98 |
+
return full
|
| 99 |
|
| 100 |
+
|
| 101 |
+
def main():
|
| 102 |
wavlm = load_frozen_wavlm()
|
| 103 |
|
|
|
|
| 104 |
manifest_rows = list(csv.DictReader(open(BATCH_DIR / "manifest.csv")))
|
| 105 |
+
new_embeddings, new_label_idx, new_ids = extract_embeddings(
|
| 106 |
wavlm, manifest_rows, BATCH_DIR / "audio"
|
| 107 |
)
|
| 108 |
|
|
|
|
| 109 |
cache_path = CACHE_DIR / "embeddings_cache.npz"
|
| 110 |
if cache_path.exists():
|
| 111 |
cache = np.load(cache_path, allow_pickle=True)
|
| 112 |
all_embeddings = np.concatenate([cache["embeddings"], new_embeddings])
|
| 113 |
+
all_label_idx = np.concatenate([cache["label_idx"], new_label_idx])
|
| 114 |
else:
|
| 115 |
+
all_embeddings, all_label_idx = new_embeddings, new_label_idx
|
| 116 |
|
| 117 |
np.savez(
|
| 118 |
OUT_DIR / "updated_embeddings_cache.npz",
|
| 119 |
embeddings=all_embeddings,
|
| 120 |
+
label_idx=all_label_idx,
|
| 121 |
)
|
| 122 |
|
| 123 |
# --- retrain the MLP head ---
|
| 124 |
# ADJUST to match app/model/classifier.py's actual MLPClassifier
|
| 125 |
+
# definition if it differs from this sklearn-style stand-in.
|
|
|
|
|
|
|
| 126 |
from sklearn.neural_network import MLPClassifier
|
|
|
|
| 127 |
|
|
|
|
|
|
|
| 128 |
head = MLPClassifier(hidden_layer_sizes=(128,), max_iter=500)
|
| 129 |
+
head.fit(all_embeddings, all_label_idx)
|
| 130 |
|
| 131 |
import joblib
|
| 132 |
+
joblib.dump({"model": head, "classes_seen": head.classes_}, OUT_DIR / "challenger_head.pt")
|
| 133 |
|
| 134 |
# --- evaluate against the PINNED held-out set ---
|
| 135 |
eval_manifest = list(csv.DictReader(open(EVAL_DIR / "manifest.csv")))
|
| 136 |
+
eval_embeddings, eval_label_idx, eval_ids = extract_embeddings(
|
| 137 |
wavlm, eval_manifest, EVAL_DIR / "audio"
|
| 138 |
)
|
| 139 |
+
|
| 140 |
+
raw_proba = head.predict_proba(eval_embeddings)
|
| 141 |
+
full_proba = expand_proba_to_full_width(raw_proba, head.classes_)
|
| 142 |
|
| 143 |
predictions_csv = OUT_DIR / "val_predictions.csv"
|
| 144 |
with open(predictions_csv, "w", newline="") as f:
|
| 145 |
writer = csv.writer(f)
|
| 146 |
+
writer.writerow(["request_id", "true_label"] + [f"prob_{i}" for i in range(NUM_CLASSES)])
|
| 147 |
+
for rid, true_idx, proba_row in zip(eval_ids, eval_label_idx, full_proba):
|
| 148 |
+
writer.writerow([rid, int(true_idx)] + [f"{p:.6f}" for p in proba_row])
|
| 149 |
|
| 150 |
+
# Reuse eval_report.py UNMODIFIED — repo must be attached as a
|
| 151 |
+
# kernel dataset_source at /kaggle/input/ser-inference-src for this
|
| 152 |
+
# subprocess call to find it.
|
| 153 |
subprocess.run(
|
| 154 |
[
|
| 155 |
"python", "/kaggle/input/ser-inference-src/scripts/eval_report.py",
|
| 156 |
"--predictions", str(predictions_csv),
|
| 157 |
"--out", str(OUT_DIR / "challenger_eval_report.json"),
|
| 158 |
+
"--corpus", "kaggle-retrain-challenger",
|
| 159 |
],
|
| 160 |
check=True,
|
| 161 |
)
|
|
|
|
| 166 |
|
| 167 |
|
| 168 |
if __name__ == "__main__":
|
| 169 |
+
main()
|
|
@@ -6,16 +6,26 @@ mode (e.g. Sad/Neutral confusion) most likely to matter in a chat context.
|
|
| 6 |
This script reports PR-AUC and per-class F1 alongside accuracy, and should
|
| 7 |
be what you lead with in any eval report — not the headline accuracy number.
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
Usage:
|
| 10 |
python scripts/eval_report.py --predictions data/val_predictions.csv \
|
| 11 |
--out data/eval_report.json
|
| 12 |
"""
|
| 13 |
import argparse
|
| 14 |
import json
|
| 15 |
-
|
| 16 |
import numpy as np
|
| 17 |
import pandas as pd
|
| 18 |
-
from sklearn.metrics import accuracy_score, average_precision_score, f1_score
|
| 19 |
|
| 20 |
IDX_TO_EMOTION = {
|
| 21 |
0: "angry", 1: "calm", 2: "disgust", 3: "fearful",
|
|
@@ -24,6 +34,14 @@ IDX_TO_EMOTION = {
|
|
| 24 |
NUM_CLASSES = 8
|
| 25 |
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
def main():
|
| 28 |
ap = argparse.ArgumentParser()
|
| 29 |
ap.add_argument("--predictions", required=True, help="CSV with true_label, prob_0..prob_7 columns")
|
|
@@ -38,6 +56,8 @@ def main():
|
|
| 38 |
|
| 39 |
accuracy = accuracy_score(labels, preds)
|
| 40 |
per_class_f1 = f1_score(labels, preds, average=None, labels=list(range(NUM_CLASSES)))
|
|
|
|
|
|
|
| 41 |
per_class_pr_auc = {}
|
| 42 |
for c in range(NUM_CLASSES):
|
| 43 |
y_bin = (labels == c).astype(int)
|
|
@@ -47,17 +67,25 @@ def main():
|
|
| 47 |
per_class_pr_auc[IDX_TO_EMOTION[c]] = float(average_precision_score(y_bin, probs[:, c]))
|
| 48 |
|
| 49 |
class_support = {IDX_TO_EMOTION[c]: int((labels == c).sum()) for c in range(NUM_CLASSES)}
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
report = {
|
| 52 |
"corpus": args.corpus,
|
| 53 |
"n_samples": len(df),
|
| 54 |
"accuracy": float(accuracy),
|
| 55 |
-
"per_class_f1":
|
|
|
|
| 56 |
"per_class_pr_auc": per_class_pr_auc,
|
| 57 |
"class_support": class_support,
|
| 58 |
-
"
|
|
|
|
|
|
|
|
|
|
| 59 |
"Low-support / low-F1 classes (e.g. sad/neutral) are the ones "
|
| 60 |
-
"most likely to matter for a chat product."
|
|
|
|
| 61 |
}
|
| 62 |
|
| 63 |
print(json.dumps(report, indent=2))
|
|
@@ -66,4 +94,4 @@ def main():
|
|
| 66 |
|
| 67 |
|
| 68 |
if __name__ == "__main__":
|
| 69 |
-
main()
|
|
|
|
| 6 |
This script reports PR-AUC and per-class F1 alongside accuracy, and should
|
| 7 |
be what you lead with in any eval report — not the headline accuracy number.
|
| 8 |
|
| 9 |
+
CHANGE (additive only — every existing key is unchanged, so existing
|
| 10 |
+
consumers like ci-eval-gate.yml keep working untouched):
|
| 11 |
+
- added per_class_recall: recall was previously not reported at all,
|
| 12 |
+
only F1 and PR-AUC. Recall specifically answers "how often do we
|
| 13 |
+
MISS this class" — the more actionable number for exactly the
|
| 14 |
+
silent-confusion failure mode this script's docstring calls out.
|
| 15 |
+
- added macro_f1 / macro_recall / macro_pr_auc: single canonical
|
| 16 |
+
aggregates, computed once here rather than downstream consumers
|
| 17 |
+
(e.g. scripts/promotion_gate.py) each re-deriving "mean across 8
|
| 18 |
+
classes" independently and risking divergence.
|
| 19 |
+
|
| 20 |
Usage:
|
| 21 |
python scripts/eval_report.py --predictions data/val_predictions.csv \
|
| 22 |
--out data/eval_report.json
|
| 23 |
"""
|
| 24 |
import argparse
|
| 25 |
import json
|
|
|
|
| 26 |
import numpy as np
|
| 27 |
import pandas as pd
|
| 28 |
+
from sklearn.metrics import accuracy_score, average_precision_score, f1_score, recall_score
|
| 29 |
|
| 30 |
IDX_TO_EMOTION = {
|
| 31 |
0: "angry", 1: "calm", 2: "disgust", 3: "fearful",
|
|
|
|
| 34 |
NUM_CLASSES = 8
|
| 35 |
|
| 36 |
|
| 37 |
+
def _macro(per_class: dict, support: dict) -> float:
|
| 38 |
+
"""Mean over classes with nonzero support only — a class with 0
|
| 39 |
+
examples in the held-out set has a degenerate 0/0 score that would
|
| 40 |
+
silently drag the average down for no real reason."""
|
| 41 |
+
values = [v for c, v in per_class.items() if support.get(c, 0) > 0]
|
| 42 |
+
return float(np.mean(values)) if values else 0.0
|
| 43 |
+
|
| 44 |
+
|
| 45 |
def main():
|
| 46 |
ap = argparse.ArgumentParser()
|
| 47 |
ap.add_argument("--predictions", required=True, help="CSV with true_label, prob_0..prob_7 columns")
|
|
|
|
| 56 |
|
| 57 |
accuracy = accuracy_score(labels, preds)
|
| 58 |
per_class_f1 = f1_score(labels, preds, average=None, labels=list(range(NUM_CLASSES)))
|
| 59 |
+
per_class_recall = recall_score(labels, preds, average=None, labels=list(range(NUM_CLASSES)))
|
| 60 |
+
|
| 61 |
per_class_pr_auc = {}
|
| 62 |
for c in range(NUM_CLASSES):
|
| 63 |
y_bin = (labels == c).astype(int)
|
|
|
|
| 67 |
per_class_pr_auc[IDX_TO_EMOTION[c]] = float(average_precision_score(y_bin, probs[:, c]))
|
| 68 |
|
| 69 |
class_support = {IDX_TO_EMOTION[c]: int((labels == c).sum()) for c in range(NUM_CLASSES)}
|
| 70 |
+
f1_dict = {IDX_TO_EMOTION[c]: float(per_class_f1[c]) for c in range(NUM_CLASSES)}
|
| 71 |
+
recall_dict = {IDX_TO_EMOTION[c]: float(per_class_recall[c]) for c in range(NUM_CLASSES)}
|
| 72 |
+
pr_auc_for_macro = {k: v for k, v in per_class_pr_auc.items() if v is not None}
|
| 73 |
|
| 74 |
report = {
|
| 75 |
"corpus": args.corpus,
|
| 76 |
"n_samples": len(df),
|
| 77 |
"accuracy": float(accuracy),
|
| 78 |
+
"per_class_f1": f1_dict,
|
| 79 |
+
"per_class_recall": recall_dict,
|
| 80 |
"per_class_pr_auc": per_class_pr_auc,
|
| 81 |
"class_support": class_support,
|
| 82 |
+
"macro_f1": _macro(f1_dict, class_support),
|
| 83 |
+
"macro_recall": _macro(recall_dict, class_support),
|
| 84 |
+
"macro_pr_auc": _macro(pr_auc_for_macro, class_support),
|
| 85 |
+
"note": "Lead with per_class_f1 / per_class_recall / per_class_pr_auc, not accuracy. "
|
| 86 |
"Low-support / low-F1 classes (e.g. sad/neutral) are the ones "
|
| 87 |
+
"most likely to matter for a chat product. macro_* fields exclude "
|
| 88 |
+
"zero-support classes from the average.",
|
| 89 |
}
|
| 90 |
|
| 91 |
print(json.dumps(report, indent=2))
|
|
|
|
| 94 |
|
| 95 |
|
| 96 |
if __name__ == "__main__":
|
| 97 |
+
main()
|
|
@@ -2,143 +2,116 @@
|
|
| 2 |
"""
|
| 3 |
scripts/promotion_gate.py — Track 1.5 decision layer.
|
| 4 |
|
| 5 |
-
eval_report.py
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
|
| 26 |
Usage:
|
| 27 |
python scripts/promotion_gate.py \
|
| 28 |
--champion-report champion_eval_report.json \
|
| 29 |
--challenger-report challenger_eval_report.json \
|
|
|
|
| 30 |
--out decision.json
|
| 31 |
-
|
| 32 |
-
This assumes eval_report.py's JSON has roughly this shape — ADJUST THE
|
| 33 |
-
KEY NAMES in `_get` calls below to match your actual output before
|
| 34 |
-
relying on this:
|
| 35 |
-
|
| 36 |
-
{
|
| 37 |
-
"accuracy": 0.81,
|
| 38 |
-
"f1": {"macro": 0.74, "per_class": {"Sad": 0.61, "Neutral": 0.70, ...}},
|
| 39 |
-
"pr_auc": {"macro": 0.79, "per_class": {"Sad": 0.68, ...}},
|
| 40 |
-
"recall": {"macro": 0.73, "per_class": {"Sad": 0.55, "Neutral": 0.66, ...}},
|
| 41 |
-
"support": {"Sad": 120, "Neutral": 340, ...}
|
| 42 |
-
}
|
| 43 |
"""
|
| 44 |
import argparse
|
| 45 |
import json
|
| 46 |
import sys
|
| 47 |
from pathlib import Path
|
| 48 |
|
| 49 |
-
|
| 50 |
-
def _get(report: dict, dotted_path: str):
|
| 51 |
-
"""Fetch a nested key like 'f1.macro' or 'recall.per_class'. Raises
|
| 52 |
-
a clear error rather than a bare KeyError if the schema doesn't match —
|
| 53 |
-
check your actual eval_report.py output and adjust the paths passed
|
| 54 |
-
on the CLI (--primary-metric, etc.) if this fires."""
|
| 55 |
-
node = report
|
| 56 |
-
for part in dotted_path.split("."):
|
| 57 |
-
if part not in node:
|
| 58 |
-
raise KeyError(
|
| 59 |
-
f"Expected key '{part}' (from '{dotted_path}') not found "
|
| 60 |
-
f"in report. Available keys at this level: {list(node.keys())}. "
|
| 61 |
-
f"Check eval_report.py's actual JSON schema and adjust "
|
| 62 |
-
f"--primary-metric / --recall-key accordingly."
|
| 63 |
-
)
|
| 64 |
-
node = node[part]
|
| 65 |
-
return node
|
| 66 |
|
| 67 |
|
| 68 |
def evaluate_policy(
|
| 69 |
champion: dict,
|
| 70 |
challenger: dict,
|
| 71 |
-
primary_metric: str,
|
| 72 |
epsilon: float,
|
| 73 |
-
recall_key: str,
|
| 74 |
per_class_tolerance: float,
|
| 75 |
-
|
| 76 |
-
|
| 77 |
) -> dict:
|
| 78 |
reasons = []
|
| 79 |
checks = {}
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
delta = chal_primary - champ_primary
|
| 85 |
primary_ok = delta >= epsilon
|
| 86 |
-
checks["
|
| 87 |
-
"
|
| 88 |
-
"
|
| 89 |
-
"challenger": chal_primary,
|
| 90 |
"delta": delta,
|
| 91 |
"required_delta": epsilon,
|
| 92 |
"passed": primary_ok,
|
| 93 |
}
|
| 94 |
if not primary_ok:
|
| 95 |
reasons.append(
|
| 96 |
-
f"
|
| 97 |
-
f"
|
| 98 |
)
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
| 103 |
per_class_failures = []
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
if
|
| 107 |
-
per_class_failures.append(f"{cls}: missing from
|
| 108 |
continue
|
| 109 |
-
|
| 110 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
per_class_failures.append(
|
| 112 |
-
f"{cls}: recall {
|
| 113 |
-
f"(champion was {
|
| 114 |
)
|
| 115 |
per_class_ok = len(per_class_failures) == 0
|
| 116 |
checks["per_class_regression"] = {
|
| 117 |
"tolerance": per_class_tolerance,
|
| 118 |
"failures": per_class_failures,
|
|
|
|
| 119 |
"passed": per_class_ok,
|
| 120 |
}
|
| 121 |
if not per_class_ok:
|
| 122 |
-
reasons.append(
|
| 123 |
-
"per-class recall regression: " + "; ".join(per_class_failures)
|
| 124 |
-
)
|
| 125 |
|
| 126 |
-
# --- Check 3 (optional): minimum support per class in eval set ---
|
| 127 |
support_ok = True
|
|
|
|
| 128 |
if min_support is not None:
|
| 129 |
-
support = _get(challenger, support_key)
|
| 130 |
low_support = {c: n for c, n in support.items() if n < min_support}
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
"min_support": min_support,
|
| 134 |
-
"low_support_classes": low_support,
|
| 135 |
-
"passed": support_ok,
|
| 136 |
-
}
|
| 137 |
-
if not support_ok:
|
| 138 |
reasons.append(
|
| 139 |
f"held-out set has classes below min_support={min_support}: "
|
| 140 |
-
f"{low_support}
|
| 141 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
promote = primary_ok and per_class_ok and support_ok
|
| 144 |
return {
|
|
@@ -153,18 +126,10 @@ def main():
|
|
| 153 |
p.add_argument("--champion-report", required=True, type=Path)
|
| 154 |
p.add_argument("--challenger-report", required=True, type=Path)
|
| 155 |
p.add_argument("--out", required=True, type=Path)
|
| 156 |
-
p.add_argument("--
|
| 157 |
-
|
| 158 |
-
p.add_argument("--
|
| 159 |
-
|
| 160 |
-
p.add_argument("--recall-key", default="recall.per_class",
|
| 161 |
-
help="Dotted path to the per-class recall dict")
|
| 162 |
-
p.add_argument("--per-class-tolerance", type=float, default=0.02,
|
| 163 |
-
help="Max allowed recall regression on any single class")
|
| 164 |
-
p.add_argument("--support-key", default="support",
|
| 165 |
-
help="Dotted path to the per-class support-count dict")
|
| 166 |
-
p.add_argument("--min-support", type=int, default=None,
|
| 167 |
-
help="If set, reject when any class has fewer than this many held-out examples")
|
| 168 |
args = p.parse_args()
|
| 169 |
|
| 170 |
champion = json.loads(args.champion_report.read_text())
|
|
@@ -173,12 +138,10 @@ def main():
|
|
| 173 |
result = evaluate_policy(
|
| 174 |
champion=champion,
|
| 175 |
challenger=challenger,
|
| 176 |
-
primary_metric=args.primary_metric,
|
| 177 |
epsilon=args.epsilon,
|
| 178 |
-
recall_key=args.recall_key,
|
| 179 |
per_class_tolerance=args.per_class_tolerance,
|
| 180 |
-
support_key=args.support_key,
|
| 181 |
min_support=args.min_support,
|
|
|
|
| 182 |
)
|
| 183 |
|
| 184 |
args.out.write_text(json.dumps(result, indent=2))
|
|
@@ -188,4 +151,4 @@ def main():
|
|
| 188 |
|
| 189 |
|
| 190 |
if __name__ == "__main__":
|
| 191 |
-
main()
|
|
|
|
| 2 |
"""
|
| 3 |
scripts/promotion_gate.py — Track 1.5 decision layer.
|
| 4 |
|
| 5 |
+
Reads eval_report.py's canonical macro_f1 and per_class_recall fields
|
| 6 |
+
directly — no longer recomputes macro F1 itself, now that eval_report.py
|
| 7 |
+
computes it once, upstream, consistently for every caller.
|
| 8 |
+
|
| 9 |
+
Policy:
|
| 10 |
+
1. macro_f1 must improve by >= --epsilon.
|
| 11 |
+
2. No individual class's RECALL may regress below
|
| 12 |
+
(champion_recall - --per-class-tolerance) — gates on recall, not
|
| 13 |
+
F1, per-class: recall is "how often do we miss this class
|
| 14 |
+
entirely," the more actionable failure mode for a chat product.
|
| 15 |
+
Skipped for any class with zero support in the eval set (0/0 is
|
| 16 |
+
not a real signal).
|
| 17 |
+
3. (optional) --min-support: flag classes below this support;
|
| 18 |
+
--strict-support makes it a hard failure instead of informational.
|
| 19 |
+
|
| 20 |
+
champion and challenger must be scored against the SAME pinned
|
| 21 |
+
held-out set, or class_support (and therefore this whole comparison)
|
| 22 |
+
won't line up.
|
| 23 |
+
|
| 24 |
+
Exit code 0 = promote, 1 = reject.
|
| 25 |
|
| 26 |
Usage:
|
| 27 |
python scripts/promotion_gate.py \
|
| 28 |
--champion-report champion_eval_report.json \
|
| 29 |
--challenger-report challenger_eval_report.json \
|
| 30 |
+
--epsilon 0.01 --per-class-tolerance 0.02 \
|
| 31 |
--out decision.json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
"""
|
| 33 |
import argparse
|
| 34 |
import json
|
| 35 |
import sys
|
| 36 |
from pathlib import Path
|
| 37 |
|
| 38 |
+
EMOTIONS = ["angry", "calm", "disgust", "fearful", "happy", "neutral", "sad", "surprised"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
|
| 41 |
def evaluate_policy(
|
| 42 |
champion: dict,
|
| 43 |
challenger: dict,
|
|
|
|
| 44 |
epsilon: float,
|
|
|
|
| 45 |
per_class_tolerance: float,
|
| 46 |
+
min_support,
|
| 47 |
+
strict_support: bool,
|
| 48 |
) -> dict:
|
| 49 |
reasons = []
|
| 50 |
checks = {}
|
| 51 |
|
| 52 |
+
champ_macro = champion["macro_f1"]
|
| 53 |
+
chal_macro = challenger["macro_f1"]
|
| 54 |
+
delta = chal_macro - champ_macro
|
|
|
|
| 55 |
primary_ok = delta >= epsilon
|
| 56 |
+
checks["macro_f1"] = {
|
| 57 |
+
"champion": champ_macro,
|
| 58 |
+
"challenger": chal_macro,
|
|
|
|
| 59 |
"delta": delta,
|
| 60 |
"required_delta": epsilon,
|
| 61 |
"passed": primary_ok,
|
| 62 |
}
|
| 63 |
if not primary_ok:
|
| 64 |
reasons.append(
|
| 65 |
+
f"macro F1 improved by {delta:.4f}, below required epsilon {epsilon:.4f} "
|
| 66 |
+
f"(champion {champ_macro:.4f} -> challenger {chal_macro:.4f})"
|
| 67 |
)
|
| 68 |
|
| 69 |
+
champ_recall = champion["per_class_recall"]
|
| 70 |
+
chal_recall = challenger["per_class_recall"]
|
| 71 |
+
support = challenger.get("class_support", {})
|
| 72 |
+
|
| 73 |
per_class_failures = []
|
| 74 |
+
skipped_zero_support = []
|
| 75 |
+
for cls in EMOTIONS:
|
| 76 |
+
if cls not in champ_recall or cls not in chal_recall:
|
| 77 |
+
per_class_failures.append(f"{cls}: missing from one of the reports")
|
| 78 |
continue
|
| 79 |
+
cls_support = support.get(cls, 0)
|
| 80 |
+
if cls_support == 0:
|
| 81 |
+
skipped_zero_support.append(cls)
|
| 82 |
+
continue
|
| 83 |
+
floor = champ_recall[cls] - per_class_tolerance
|
| 84 |
+
if chal_recall[cls] < floor:
|
| 85 |
per_class_failures.append(
|
| 86 |
+
f"{cls}: recall {chal_recall[cls]:.4f} < floor {floor:.4f} "
|
| 87 |
+
f"(champion was {champ_recall[cls]:.4f}, support={cls_support})"
|
| 88 |
)
|
| 89 |
per_class_ok = len(per_class_failures) == 0
|
| 90 |
checks["per_class_regression"] = {
|
| 91 |
"tolerance": per_class_tolerance,
|
| 92 |
"failures": per_class_failures,
|
| 93 |
+
"skipped_zero_support_classes": skipped_zero_support,
|
| 94 |
"passed": per_class_ok,
|
| 95 |
}
|
| 96 |
if not per_class_ok:
|
| 97 |
+
reasons.append("per-class recall regression: " + "; ".join(per_class_failures))
|
|
|
|
|
|
|
| 98 |
|
|
|
|
| 99 |
support_ok = True
|
| 100 |
+
low_support = {}
|
| 101 |
if min_support is not None:
|
|
|
|
| 102 |
low_support = {c: n for c, n in support.items() if n < min_support}
|
| 103 |
+
if low_support and strict_support:
|
| 104 |
+
support_ok = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
reasons.append(
|
| 106 |
f"held-out set has classes below min_support={min_support}: "
|
| 107 |
+
f"{low_support} (strict mode — treating as reject)"
|
| 108 |
)
|
| 109 |
+
checks["min_support"] = {
|
| 110 |
+
"min_support": min_support,
|
| 111 |
+
"low_support_classes": low_support,
|
| 112 |
+
"strict": strict_support,
|
| 113 |
+
"passed": support_ok,
|
| 114 |
+
}
|
| 115 |
|
| 116 |
promote = primary_ok and per_class_ok and support_ok
|
| 117 |
return {
|
|
|
|
| 126 |
p.add_argument("--champion-report", required=True, type=Path)
|
| 127 |
p.add_argument("--challenger-report", required=True, type=Path)
|
| 128 |
p.add_argument("--out", required=True, type=Path)
|
| 129 |
+
p.add_argument("--epsilon", type=float, default=0.01)
|
| 130 |
+
p.add_argument("--per-class-tolerance", type=float, default=0.02)
|
| 131 |
+
p.add_argument("--min-support", type=int, default=None)
|
| 132 |
+
p.add_argument("--strict-support", action="store_true")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
args = p.parse_args()
|
| 134 |
|
| 135 |
champion = json.loads(args.champion_report.read_text())
|
|
|
|
| 138 |
result = evaluate_policy(
|
| 139 |
champion=champion,
|
| 140 |
challenger=challenger,
|
|
|
|
| 141 |
epsilon=args.epsilon,
|
|
|
|
| 142 |
per_class_tolerance=args.per_class_tolerance,
|
|
|
|
| 143 |
min_support=args.min_support,
|
| 144 |
+
strict_support=args.strict_support,
|
| 145 |
)
|
| 146 |
|
| 147 |
args.out.write_text(json.dumps(result, indent=2))
|
|
|
|
| 151 |
|
| 152 |
|
| 153 |
if __name__ == "__main__":
|
| 154 |
+
main()
|