Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions brainscore_language/models/conftest.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,24 @@
"""
Shared pytest fixtures for all model tests.

Some HuggingFace models (e.g. Gemma) are "gated" -- they require an authenticated
token to download weights. This conftest provides a session-scoped fixture that
automatically fetches a HuggingFace read token from AWS Secrets Manager and logs in
before any model test runs. If the HF_TOKEN environment variable is already set
(e.g. via `huggingface-cli login` or manual export), the AWS lookup is skipped.
"""Authentication for model tests that explicitly request ``set_hf_token``.

Because this file lives in brainscore_language/models/, pytest automatically applies
its fixtures to every test in this directory and all model subdirectories (gemma/,
gpt/, etc.), so individual test files don't need any auth boilerplate.
Public and local models do not need credentials. Gated-model test modules can
use ``pytestmark = pytest.mark.usefixtures("set_hf_token")``. An existing
HF_TOKEN takes precedence over the CI secret lookup.
"""

import json
import os

import boto3
import pytest
from huggingface_hub import login


@pytest.fixture(autouse=True, scope="session")
@pytest.fixture(scope="session")
def set_hf_token():
"""Pull HuggingFace token from AWS Secrets Manager if not already set."""
if os.environ.get("HF_TOKEN"):
return
import boto3
from huggingface_hub import login

try:
client = boto3.client("secretsmanager", region_name="us-east-2")
resp = client.get_secret_value(SecretId="hugging_face_read_token")
Expand Down
2 changes: 2 additions & 0 deletions brainscore_language/models/gemma/test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import numpy as np
import pytest

pytestmark = pytest.mark.usefixtures("set_hf_token")

from brainscore_language import load_model
from brainscore_language.artificial_subject import ArtificialSubject

Expand Down
3 changes: 2 additions & 1 deletion brainscore_language/models/glove/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ def _prepare_weights(name):
if not weights_file.is_file():
# download zip
zip_filename = f"{name}.zip"
url = f'https://nlp.stanford.edu/data/{zip_filename}'
# Stanford's official mirror hosts the original pretrained vectors.
url = f'https://huggingface.co/stanfordnlp/glove/resolve/main/{zip_filename}'
_logger.info(f"Downloading weights zip from {url} to {zip_filename}")
urlretrieve(url, zip_filename)
# unzip
Expand Down
7 changes: 7 additions & 0 deletions brainscore_language/models/suma/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""SUMA uses a gated Llama tokenizer."""
import pytest


@pytest.fixture(autouse=True)
def authenticate_suma(set_hf_token):
"""Request the shared authentication fixture for SUMA tests."""
43 changes: 43 additions & 0 deletions tests/test_model_helpers/test_glove_download.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Check download routing with a tiny archive, without model inference."""
import importlib.util
from pathlib import Path
import zipfile

import pytest


@pytest.fixture
def glove_module(tmp_path, monkeypatch):
source = Path(__file__).parents[2] / 'brainscore_language/models/glove/model.py'
spec = importlib.util.spec_from_file_location('glove_download_under_test', source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
monkeypatch.setattr(module, '__file__', str(tmp_path / 'model.py'))
monkeypatch.chdir(tmp_path)
return module


def test_download_original_vectors_from_official_host(glove_module, monkeypatch):
calls = []

def download(url, filename):
calls.append(url)
with zipfile.ZipFile(filename, 'w') as archive:
archive.writestr('glove.840B.300d.txt', 'test 0.1 0.2\n')

monkeypatch.setattr(glove_module, 'urlretrieve', download)
result = glove_module._prepare_weights('glove.840B.300d')
assert result.read_text() == 'test 0.1 0.2\n'
assert calls == ['https://huggingface.co/stanfordnlp/glove/resolve/main/glove.840B.300d.zip']
assert not Path('glove.840B.300d.zip').exists()
assert glove_module._prepare_weights('glove.840B.300d') == result
assert len(calls) == 1


def test_download_failure_remains_a_failure(glove_module, monkeypatch):
def download(*args):
raise OSError('unreachable')

monkeypatch.setattr(glove_module, 'urlretrieve', download)
with pytest.raises(OSError, match='unreachable'):
glove_module._prepare_weights('glove.840B.300d')
38 changes: 38 additions & 0 deletions tests/test_model_helpers/test_model_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Public model tests must run even when no credentials are available."""
from pathlib import Path
import os
import shutil
import subprocess
import sys

import pytest


@pytest.mark.parametrize('gated, token, expected', [
(False, False, '1 passed'),
(True, False, '1 skipped'),
(True, True, '1 passed'),
])
def test_auth_is_requested_only_for_gated_models(tmp_path, gated, token, expected):
source = Path(__file__).parents[2] / 'brainscore_language/models/conftest.py'
shutil.copyfile(source, tmp_path / 'conftest.py')
# A public test must never try either authentication service.
(tmp_path / 'boto3.py').write_text(
'def client(*args, **kwargs):\n raise RuntimeError("no credentials")\n')
(tmp_path / 'huggingface_hub.py').write_text(
'def login(*args, **kwargs):\n raise AssertionError("unexpected login")\n')
marker = '@pytest.mark.usefixtures("set_hf_token")\n' if gated else ''
(tmp_path / 'test_model.py').write_text(
'import pytest\n' + marker + 'def test_model():\n assert True\n')
environment = dict(os.environ)
environment.pop('HF_TOKEN', None)
environment['PYTHONPATH'] = str(tmp_path)
environment['PYTEST_DISABLE_PLUGIN_AUTOLOAD'] = '1'
if token:
environment['HF_TOKEN'] = 'test-token-not-used-for-network'
result = subprocess.run(
[sys.executable, '-m', 'pytest', '-q', str(tmp_path)],
cwd=tmp_path, env=environment, capture_output=True, text=True, timeout=30,
)
assert result.returncode == 0, result.stdout + result.stderr
assert expected in result.stdout
Loading