Use HF_HUB_OFFLINE + fix has_file in offline mode (#31016)
* Fix has_file in offline mode * harmonize env variable for offline mode * Switch to HF_HUB_OFFLINE * fix test * revert test_offline to test TRANSFORMERS_OFFLINE * Add new offline test * merge conflicts * docs
This commit is contained in:
@@ -12,7 +12,6 @@
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
|
||||
@@ -18,6 +18,7 @@ import unittest
|
||||
import unittest.mock as mock
|
||||
from pathlib import Path
|
||||
|
||||
from huggingface_hub import hf_hub_download
|
||||
from requests.exceptions import HTTPError
|
||||
|
||||
from transformers.utils import (
|
||||
@@ -33,6 +34,7 @@ from transformers.utils import (
|
||||
|
||||
|
||||
RANDOM_BERT = "hf-internal-testing/tiny-random-bert"
|
||||
TINY_BERT_PT_ONLY = "hf-internal-testing/tiny-bert-pt-only"
|
||||
CACHE_DIR = os.path.join(TRANSFORMERS_CACHE, "models--hf-internal-testing--tiny-random-bert")
|
||||
FULL_COMMIT_HASH = "9b8c223d42b2188cb49d29af482996f9d0f3e5a6"
|
||||
|
||||
@@ -99,9 +101,20 @@ class GetFromCacheTests(unittest.TestCase):
|
||||
mock_head.assert_called()
|
||||
|
||||
def test_has_file(self):
|
||||
self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only", WEIGHTS_NAME))
|
||||
self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only", TF2_WEIGHTS_NAME))
|
||||
self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only", FLAX_WEIGHTS_NAME))
|
||||
self.assertTrue(has_file(TINY_BERT_PT_ONLY, WEIGHTS_NAME))
|
||||
self.assertFalse(has_file(TINY_BERT_PT_ONLY, TF2_WEIGHTS_NAME))
|
||||
self.assertFalse(has_file(TINY_BERT_PT_ONLY, FLAX_WEIGHTS_NAME))
|
||||
|
||||
def test_has_file_in_cache(self):
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
# Empty cache dir + offline mode => return False
|
||||
assert not has_file(TINY_BERT_PT_ONLY, WEIGHTS_NAME, local_files_only=True, cache_dir=tmp_dir)
|
||||
|
||||
# Populate cache dir
|
||||
hf_hub_download(TINY_BERT_PT_ONLY, WEIGHTS_NAME, cache_dir=tmp_dir)
|
||||
|
||||
# Cache dir + offline mode => return True
|
||||
assert has_file(TINY_BERT_PT_ONLY, WEIGHTS_NAME, local_files_only=True, cache_dir=tmp_dir)
|
||||
|
||||
def test_get_file_from_repo_distant(self):
|
||||
# `get_file_from_repo` returns None if the file does not exist
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Tuple
|
||||
|
||||
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
|
||||
from transformers.testing_utils import TestCasePlus, require_torch
|
||||
@@ -56,15 +57,9 @@ socket.socket = offline_socket
|
||||
pipeline(task="fill-mask", model=mname)
|
||||
|
||||
# baseline - just load from_pretrained with normal network
|
||||
cmd = [sys.executable, "-c", "\n".join([load, run, mock])]
|
||||
|
||||
# should succeed
|
||||
env = self.get_env()
|
||||
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
|
||||
env["TRANSFORMERS_OFFLINE"] = "1"
|
||||
result = subprocess.run(cmd, env=env, check=False, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("success", result.stdout.decode())
|
||||
stdout, _ = self._execute_with_env(load, run, mock, TRANSFORMERS_OFFLINE="1")
|
||||
self.assertIn("success", stdout)
|
||||
|
||||
@require_torch
|
||||
def test_offline_mode_no_internet(self):
|
||||
@@ -97,13 +92,9 @@ socket.socket = offline_socket
|
||||
pipeline(task="fill-mask", model=mname)
|
||||
|
||||
# baseline - just load from_pretrained with normal network
|
||||
cmd = [sys.executable, "-c", "\n".join([load, run, mock])]
|
||||
|
||||
# should succeed
|
||||
env = self.get_env()
|
||||
result = subprocess.run(cmd, env=env, check=False, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("success", result.stdout.decode())
|
||||
stdout, _ = self._execute_with_env(load, run, mock)
|
||||
self.assertIn("success", stdout)
|
||||
|
||||
@require_torch
|
||||
def test_offline_mode_sharded_checkpoint(self):
|
||||
@@ -132,27 +123,17 @@ socket.socket = offline_socket
|
||||
"""
|
||||
|
||||
# baseline - just load from_pretrained with normal network
|
||||
cmd = [sys.executable, "-c", "\n".join([load, run])]
|
||||
|
||||
# should succeed
|
||||
env = self.get_env()
|
||||
result = subprocess.run(cmd, env=env, check=False, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("success", result.stdout.decode())
|
||||
stdout, _ = self._execute_with_env(load, run)
|
||||
self.assertIn("success", stdout)
|
||||
|
||||
# next emulate no network
|
||||
cmd = [sys.executable, "-c", "\n".join([load, mock, run])]
|
||||
|
||||
# Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
|
||||
# env["TRANSFORMERS_OFFLINE"] = "0"
|
||||
# result = subprocess.run(cmd, env=env, check=False, capture_output=True)
|
||||
# self.assertEqual(result.returncode, 1, result.stderr)
|
||||
# self._execute_with_env(load, mock, run, should_fail=True, TRANSFORMERS_OFFLINE="0")
|
||||
|
||||
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
|
||||
env["TRANSFORMERS_OFFLINE"] = "1"
|
||||
result = subprocess.run(cmd, env=env, check=False, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("success", result.stdout.decode())
|
||||
stdout, _ = self._execute_with_env(load, mock, run, TRANSFORMERS_OFFLINE="1")
|
||||
self.assertIn("success", stdout)
|
||||
|
||||
@require_torch
|
||||
def test_offline_mode_pipeline_exception(self):
|
||||
@@ -169,14 +150,11 @@ import socket
|
||||
def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")
|
||||
socket.socket = offline_socket
|
||||
"""
|
||||
env = self.get_env()
|
||||
env["TRANSFORMERS_OFFLINE"] = "1"
|
||||
cmd = [sys.executable, "-c", "\n".join([load, mock, run])]
|
||||
result = subprocess.run(cmd, env=env, check=False, capture_output=True)
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
|
||||
_, stderr = self._execute_with_env(load, mock, run, should_fail=True, TRANSFORMERS_OFFLINE="1")
|
||||
self.assertIn(
|
||||
"You cannot infer task automatically within `pipeline` when using offline mode",
|
||||
result.stderr.decode().replace("\n", ""),
|
||||
stderr.replace("\n", ""),
|
||||
)
|
||||
|
||||
@require_torch
|
||||
@@ -191,16 +169,51 @@ print("success")
|
||||
"""
|
||||
|
||||
# baseline - just load from_pretrained with normal network
|
||||
cmd = [sys.executable, "-c", "\n".join([load, run])]
|
||||
|
||||
# should succeed
|
||||
env = self.get_env()
|
||||
result = subprocess.run(cmd, env=env, check=False, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("success", result.stdout.decode())
|
||||
stdout, _ = self._execute_with_env(load, run)
|
||||
self.assertIn("success", stdout)
|
||||
|
||||
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
|
||||
env["TRANSFORMERS_OFFLINE"] = "1"
|
||||
result = subprocess.run(cmd, env=env, check=False, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("success", result.stdout.decode())
|
||||
stdout, _ = self._execute_with_env(load, run, TRANSFORMERS_OFFLINE="1")
|
||||
self.assertIn("success", stdout)
|
||||
|
||||
def test_is_offline_mode(self):
|
||||
"""
|
||||
Test `_is_offline_mode` helper (should respect both HF_HUB_OFFLINE and legacy TRANSFORMERS_OFFLINE env vars)
|
||||
"""
|
||||
load = "from transformers.utils import is_offline_mode"
|
||||
run = "print(is_offline_mode())"
|
||||
|
||||
stdout, _ = self._execute_with_env(load, run)
|
||||
self.assertIn("False", stdout)
|
||||
|
||||
stdout, _ = self._execute_with_env(load, run, TRANSFORMERS_OFFLINE="1")
|
||||
self.assertIn("True", stdout)
|
||||
|
||||
stdout, _ = self._execute_with_env(load, run, HF_HUB_OFFLINE="1")
|
||||
self.assertIn("True", stdout)
|
||||
|
||||
def _execute_with_env(self, *commands: Tuple[str, ...], should_fail: bool = False, **env) -> Tuple[str, str]:
|
||||
"""Execute Python code with a given environment and return the stdout/stderr as strings.
|
||||
|
||||
If `should_fail=True`, the command is expected to fail. Otherwise, it should succeed.
|
||||
Environment variables can be passed as keyword arguments.
|
||||
"""
|
||||
# Build command
|
||||
cmd = [sys.executable, "-c", "\n".join(commands)]
|
||||
|
||||
# Configure env
|
||||
new_env = self.get_env()
|
||||
new_env.update(env)
|
||||
|
||||
# Run command
|
||||
result = subprocess.run(cmd, env=new_env, check=False, capture_output=True)
|
||||
|
||||
# Check execution
|
||||
if should_fail:
|
||||
self.assertNotEqual(result.returncode, 0, result.stderr)
|
||||
else:
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
# Return output
|
||||
return result.stdout.decode(), result.stderr.decode()
|
||||
|
||||
Reference in New Issue
Block a user