code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def check_unix_fs_mocked(
tmpdir: Any, mocker: MockerFixture
) -> Callable[[Any, Any], None]:
"""
performs a standard test in a UnixFS, assuming that both `os.remove` and
`os.listdir` have been mocked previously.
"""
def check(mocked_rm, mocked_ls):
assert mocked_rm is os.remove
... |
performs a standard test in a UnixFS, assuming that both `os.remove` and
`os.listdir` have been mocked previously.
| check_unix_fs_mocked | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_mock_patches(
mock_fs: Any,
mocker: MockerFixture,
check_unix_fs_mocked: Callable[[Any, Any], None],
) -> None:
"""
Installs mocks into `os` functions and performs a standard testing of
mock functionality. We parametrize different mock methods to ensure
all (intended, at least) mock... |
Installs mocks into `os` functions and performs a standard testing of
mock functionality. We parametrize different mock methods to ensure
all (intended, at least) mock API is covered.
| test_mock_patches | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_mock_patch_dict_resetall(mocker: MockerFixture) -> None:
"""
We can call resetall after patching a dict.
:param mock:
"""
x = {"original": 1}
mocker.patch.dict(x, values=[("new", 10)], clear=True)
assert x == {"new": 10}
mocker.resetall()
assert x == {"new": 10} |
We can call resetall after patching a dict.
:param mock:
| test_mock_patch_dict_resetall | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def assert_traceback() -> Generator[None, None, None]:
"""
Assert that this file is at the top of the filtered traceback
"""
try:
yield
except AssertionError as e:
assert e.__traceback__.tb_frame.f_code.co_filename == __file__ # type:ignore
else:
raise AssertionError("DI... |
Assert that this file is at the top of the filtered traceback
| assert_traceback | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def assert_argument_introspection(left: Any, right: Any) -> Generator[None, None, None]:
"""
Assert detailed argument introspection is used
"""
try:
yield
except AssertionError as e:
# this may be a bit too assuming, but seems nicer then hard-coding
import _pytest.assertion.u... |
Assert detailed argument introspection is used
| assert_argument_introspection | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_patched_method_parameter_name(mocker: MockerFixture) -> None:
"""Test that our internal code uses uncommon names when wrapping other
"mock" methods to avoid conflicts with user code (#31).
"""
class Request:
@classmethod
def request(cls, method, args):
pass
m =... | Test that our internal code uses uncommon names when wrapping other
"mock" methods to avoid conflicts with user code (#31).
| test_patched_method_parameter_name | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_monkeypatch_native(testdir: Any) -> None:
"""Automatically disable monkeypatching when --tb=native."""
testdir.makepyfile(
"""
def test_foo(mocker):
stub = mocker.stub()
stub(1, greet='hello')
stub.assert_called_once_with(1, greet='hey')
"""
)... | Automatically disable monkeypatching when --tb=native. | test_monkeypatch_native | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_standalone_mock(testdir: Any) -> None:
"""Check that the "mock_use_standalone" is being used."""
pytest.importorskip("mock")
testdir.makepyfile(
"""
import mock
def test_foo(mocker):
assert mock.MagicMock is mocker.MagicMock
"""
)
testdir.makeini(
... | Check that the "mock_use_standalone" is being used. | test_standalone_mock | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_assert_called_with_unicode_arguments(mocker: MockerFixture) -> None:
"""Test bug in assert_call_with called with non-ascii unicode string (#91)"""
stub = mocker.stub()
stub(b"l\xc3\xb6k".decode("UTF-8"))
with pytest.raises(AssertionError):
stub.assert_called_with("lak") | Test bug in assert_call_with called with non-ascii unicode string (#91) | test_assert_called_with_unicode_arguments | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_plain_stopall(testdir: Any) -> None:
"""patch.stopall() in a test should not cause an error during unconfigure (#137)"""
testdir.makeini(
"""
[pytest]
asyncio_mode=auto
"""
)
testdir.makepyfile(
"""
import random
def get_random_number():
... | patch.stopall() in a test should not cause an error during unconfigure (#137) | test_plain_stopall | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_context_manager_patch_example(mocker: MockerFixture) -> None:
"""Our message about misusing mocker as a context manager should not affect mocking
context managers (see #192)"""
class dummy_module:
class MyContext:
def __enter__(self, *args, **kwargs):
return 10
... | Our message about misusing mocker as a context manager should not affect mocking
context managers (see #192) | test_context_manager_patch_example | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_patch_context_manager_with_context_manager(mocker: MockerFixture) -> None:
"""Test that no warnings are issued when an object patched with
patch.context_manager is used as a context manager (#221)"""
class A:
def doIt(self):
return False
a = A()
with warnings.catch_wa... | Test that no warnings are issued when an object patched with
patch.context_manager is used as a context manager (#221) | test_patch_context_manager_with_context_manager | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def test_abort_patch_context_manager_with_stale_pyc(testdir: Any) -> None:
"""Ensure we don't trigger an error in case the frame where mocker.patch is being
used doesn't have a 'context' (#169)"""
import compileall
py_fn = testdir.makepyfile(
c="""
class C:
x = 1
de... | Ensure we don't trigger an error in case the frame where mocker.patch is being
used doesn't have a 'context' (#169) | test_abort_patch_context_manager_with_stale_pyc | python | pytest-dev/pytest-mock | tests/test_pytest_mock.py | https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py | MIT |
def block_expansion(
model_name_or_path: str,
output_dir: str,
num_expand: int,
shard_size: str = "5GB",
save_safetensors: bool = True,
):
r"""Perform block expansion for LLaMA, Mistral, Qwen2 or Yi models.
Usage: python llama_pro.py --model_name_or_path meta-llama/Llama-2-7b-hf --output_di... | Perform block expansion for LLaMA, Mistral, Qwen2 or Yi models.
Usage: python llama_pro.py --model_name_or_path meta-llama/Llama-2-7b-hf --output_dir llama2_pro --num_expand 8
| block_expansion | python | hiyouga/LLaMA-Factory | scripts/llama_pro.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/llama_pro.py | Apache-2.0 |
def quantize_loftq(
model_name_or_path: str,
output_dir: str,
loftq_bits: int = 4,
loftq_iter: int = 4,
lora_alpha: int = None,
lora_rank: int = 16,
lora_dropout: float = 0,
lora_target: tuple = ("q_proj", "v_proj"),
save_safetensors: bool = True,
):
r"""Initialize LoRA weights w... | Initialize LoRA weights with LoRA-fine-tuning-aware Quantization (LoftQ).
Usage: python loftq_init.py --model_name_or_path path_to_model --output_dir output_dir
| quantize_loftq | python | hiyouga/LLaMA-Factory | scripts/loftq_init.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/loftq_init.py | Apache-2.0 |
def quantize_pissa(
model_name_or_path: str,
output_dir: str,
pissa_iter: int = 16,
lora_alpha: int = None,
lora_rank: int = 16,
lora_dropout: float = 0,
lora_target: tuple = ("q_proj", "v_proj"),
save_safetensors: bool = True,
):
r"""Initialize LoRA weights with Principal Singular v... | Initialize LoRA weights with Principal Singular values and Singular vectors Adaptation (PiSSA).
Usage: python pissa_init.py --model_name_or_path path_to_model --output_dir output_dir
| quantize_pissa | python | hiyouga/LLaMA-Factory | scripts/pissa_init.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/pissa_init.py | Apache-2.0 |
def merge_lora(
base_model_path: str,
lora_checkpoint_path: str,
extra_file: str = "spk_dict.pt",
submodule_name: str = "thinker",
save_path: str = "./merged_model_checkpoint",
):
"""Load the original model, merge the LoRA weights.
For a specified submodule, and save the final merged model ... | Load the original model, merge the LoRA weights.
For a specified submodule, and save the final merged model along with its configurations.
Args:
base_model_path (str): Path to the original model directory.
lora_checkpoint_path (str): Path to the directory containing LoRA weights.
extra... | merge_lora | python | hiyouga/LLaMA-Factory | scripts/qwen_omni_merge.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/qwen_omni_merge.py | Apache-2.0 |
def save_full_model(
saved_thinker_path: str,
base_model_path: str,
save_path: str = "./merged_model_checkpoint",
extra_file: str = "spk_dict.pt",
):
"""Load the saved thinker module and the original model, replace the thinker in the original model.
Then save the complete model along with its t... | Load the saved thinker module and the original model, replace the thinker in the original model.
Then save the complete model along with its tokenizer and processor configuration.
Args:
saved_thinker_path (str): Path to the saved thinker weights.
base_model_path (str): Directory path of the or... | save_full_model | python | hiyouga/LLaMA-Factory | scripts/qwen_omni_merge.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/qwen_omni_merge.py | Apache-2.0 |
def vllm_infer(
model_name_or_path: str,
adapter_name_or_path: str = None,
dataset: str = "alpaca_en_demo",
dataset_dir: str = "data",
template: str = "default",
cutoff_len: int = 2048,
max_samples: Optional[int] = None,
vllm_config: str = "{}",
save_name: str = "generated_prediction... | Perform batch generation using vLLM engine, which supports tensor parallelism.
Usage: python vllm_infer.py --model_name_or_path meta-llama/Llama-2-7b-hf --template llama --dataset alpaca_en_demo
| vllm_infer | python | hiyouga/LLaMA-Factory | scripts/vllm_infer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/vllm_infer.py | Apache-2.0 |
def llamafy_baichuan2(
input_dir: str,
output_dir: str,
shard_size: str = "2GB",
save_safetensors: bool = True,
):
r"""Convert the Baichuan2-7B model in the same format as LLaMA2-7B.
Usage: python llamafy_baichuan2.py --input_dir input --output_dir output
Converted model: https://huggingfac... | Convert the Baichuan2-7B model in the same format as LLaMA2-7B.
Usage: python llamafy_baichuan2.py --input_dir input --output_dir output
Converted model: https://huggingface.co/hiyouga/Baichuan2-7B-Base-LLaMAfied
| llamafy_baichuan2 | python | hiyouga/LLaMA-Factory | scripts/convert_ckpt/llamafy_baichuan2.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/convert_ckpt/llamafy_baichuan2.py | Apache-2.0 |
def llamafy_qwen(
input_dir: str,
output_dir: str,
shard_size: str = "2GB",
save_safetensors: bool = False,
):
r"""Convert the Qwen models in the same format as LLaMA2.
Usage: python llamafy_qwen.py --input_dir input --output_dir output
Converted model: https://huggingface.co/hiyouga/Qwen-1... | Convert the Qwen models in the same format as LLaMA2.
Usage: python llamafy_qwen.py --input_dir input --output_dir output
Converted model: https://huggingface.co/hiyouga/Qwen-14B-Chat-LLaMAfied
| llamafy_qwen | python | hiyouga/LLaMA-Factory | scripts/convert_ckpt/llamafy_qwen.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/convert_ckpt/llamafy_qwen.py | Apache-2.0 |
def calculate_flops(
model_name_or_path: str,
batch_size: int = 1,
seq_length: int = 512,
flash_attn: str = "auto",
):
r"""Calculate the flops of pre-trained models.
Usage: python cal_flops.py --model_name_or_path path_to_model --batch_size 1 --seq_length 512
"""
with get_accelerator().... | Calculate the flops of pre-trained models.
Usage: python cal_flops.py --model_name_or_path path_to_model --batch_size 1 --seq_length 512
| calculate_flops | python | hiyouga/LLaMA-Factory | scripts/stat_utils/cal_flops.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/stat_utils/cal_flops.py | Apache-2.0 |
def calculate_lr(
model_name_or_path: str,
batch_size: int, # total batch size, namely (batch size * gradient accumulation * world size)
stage: Literal["pt", "sft"] = "sft",
dataset: str = "alpaca_en_demo",
dataset_dir: str = "data",
template: str = "default",
cutoff_len: int = 2048, # i.e... | Calculate the optimal learning rate for 7B/13B models using LLaMA's hyper-parameters.
Usage:
python cal_lr.py --model_name_or_path path_to_model --dataset alpaca_en_demo --cutoff_len 1024 --batch_size 16
| calculate_lr | python | hiyouga/LLaMA-Factory | scripts/stat_utils/cal_lr.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/stat_utils/cal_lr.py | Apache-2.0 |
def compute_model_flops(
model_name_or_path: str,
total_batch_size: int,
seq_length: int,
include_backward: bool = True,
include_recompute: bool = False,
include_flashattn: bool = False,
) -> int:
r"""Calculate the FLOPs of model per forward/backward pass."""
config = AutoConfig.from_pre... | Calculate the FLOPs of model per forward/backward pass. | compute_model_flops | python | hiyouga/LLaMA-Factory | scripts/stat_utils/cal_mfu.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/stat_utils/cal_mfu.py | Apache-2.0 |
def compute_device_flops(world_size: int) -> float:
r"""Calculate the FLOPs of the device capability per second."""
device_name = torch.cuda.get_device_name()
if "H100" in device_name or "H800" in device_name:
return 989 * 1e12 * world_size
elif "A100" in device_name or "A800" in device_name:
... | Calculate the FLOPs of the device capability per second. | compute_device_flops | python | hiyouga/LLaMA-Factory | scripts/stat_utils/cal_mfu.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/stat_utils/cal_mfu.py | Apache-2.0 |
def calculate_mfu(
model_name_or_path: str,
batch_size: int = 1,
seq_length: int = 1024,
num_steps: int = 100,
finetuning_type: str = "lora",
flash_attn: str = "auto",
deepspeed_stage: int = 0,
disable_gc: bool = False,
liger_kernel: bool = False,
unsloth_gc: bool = False,
) -> f... | Calculate MFU for given model and hyper-params.
Usage: python cal_mfu.py --model_name_or_path path_to_model --batch_size 1 --seq_length 1024
| calculate_mfu | python | hiyouga/LLaMA-Factory | scripts/stat_utils/cal_mfu.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/stat_utils/cal_mfu.py | Apache-2.0 |
def __call__(self, features: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
r"""Pad batched data to the longest sequence in the batch."""
chosen_features = []
for feature in features:
chosen_features.append(
{
"input_ids": feature["chosen_input_... | Pad batched data to the longest sequence in the batch. | __call__ | python | hiyouga/LLaMA-Factory | scripts/stat_utils/cal_ppl.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/stat_utils/cal_ppl.py | Apache-2.0 |
def calculate_ppl(
model_name_or_path: str,
save_name: str = "ppl.json",
batch_size: int = 4,
stage: Literal["pt", "sft", "rm"] = "sft",
dataset: str = "alpaca_en_demo",
dataset_dir: str = "data",
template: str = "default",
cutoff_len: int = 2048,
max_samples: Optional[int] = None,
... | Calculate the ppl on the dataset of the pre-trained models.
Usage: export CUDA_VISIBLE_DEVICES=0
python cal_ppl.py --model_name_or_path path_to_model --dataset alpaca_en_demo --save_name ppl.json
| calculate_ppl | python | hiyouga/LLaMA-Factory | scripts/stat_utils/cal_ppl.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/stat_utils/cal_ppl.py | Apache-2.0 |
def length_cdf(
model_name_or_path: str,
dataset: str = "alpaca_en_demo",
dataset_dir: str = "data",
template: str = "default",
interval: int = 1000,
):
r"""Calculate the distribution of the input lengths in the dataset.
Usage: export CUDA_VISIBLE_DEVICES=0
python length_cdf.py --model_... | Calculate the distribution of the input lengths in the dataset.
Usage: export CUDA_VISIBLE_DEVICES=0
python length_cdf.py --model_name_or_path path_to_model --dataset alpaca_en_demo --template default
| length_cdf | python | hiyouga/LLaMA-Factory | scripts/stat_utils/length_cdf.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/scripts/stat_utils/length_cdf.py | Apache-2.0 |
async def chat(
self,
messages: list[dict[str, str]],
system: Optional[str] = None,
tools: Optional[str] = None,
images: Optional[list["ImageInput"]] = None,
videos: Optional[list["VideoInput"]] = None,
audios: Optional[list["AudioInput"]] = None,
**input_... | Get a list of responses of the chat model. | chat | python | hiyouga/LLaMA-Factory | src/llamafactory/chat/base_engine.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/chat/base_engine.py | Apache-2.0 |
async def stream_chat(
self,
messages: list[dict[str, str]],
system: Optional[str] = None,
tools: Optional[str] = None,
images: Optional[list["ImageInput"]] = None,
videos: Optional[list["VideoInput"]] = None,
audios: Optional[list["AudioInput"]] = None,
*... | Get the response token-by-token of the chat model. | stream_chat | python | hiyouga/LLaMA-Factory | src/llamafactory/chat/base_engine.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/chat/base_engine.py | Apache-2.0 |
async def get_scores(
self,
batch_input: list[str],
**input_kwargs,
) -> list[float]:
r"""Get a list of scores of the reward model."""
... | Get a list of scores of the reward model. | get_scores | python | hiyouga/LLaMA-Factory | src/llamafactory/chat/base_engine.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/chat/base_engine.py | Apache-2.0 |
async def achat(
self,
messages: list[dict[str, str]],
system: Optional[str] = None,
tools: Optional[str] = None,
images: Optional[list["ImageInput"]] = None,
videos: Optional[list["VideoInput"]] = None,
audios: Optional[list["AudioInput"]] = None,
**input... | Asynchronously get a list of responses of the chat model. | achat | python | hiyouga/LLaMA-Factory | src/llamafactory/chat/chat_model.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/chat/chat_model.py | Apache-2.0 |
async def astream_chat(
self,
messages: list[dict[str, str]],
system: Optional[str] = None,
tools: Optional[str] = None,
images: Optional[list["ImageInput"]] = None,
videos: Optional[list["VideoInput"]] = None,
audios: Optional[list["AudioInput"]] = None,
... | Asynchronously get the response token-by-token of the chat model. | astream_chat | python | hiyouga/LLaMA-Factory | src/llamafactory/chat/chat_model.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/chat/chat_model.py | Apache-2.0 |
async def aget_scores(
self,
batch_input: list[str],
**input_kwargs,
) -> list[float]:
r"""Asynchronously get a list of scores of the reward model."""
return await self.engine.get_scores(batch_input, **input_kwargs) | Asynchronously get a list of scores of the reward model. | aget_scores | python | hiyouga/LLaMA-Factory | src/llamafactory/chat/chat_model.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/chat/chat_model.py | Apache-2.0 |
def _cleanup_server(self):
r"""Clean up the server process when the engine is destroyed."""
if hasattr(self, "server_process") and self.server_process:
try:
logger.info("Terminating SGLang server process")
terminate_process(self.server_process)
... | Clean up the server process when the engine is destroyed. | _cleanup_server | python | hiyouga/LLaMA-Factory | src/llamafactory/chat/sglang_engine.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/chat/sglang_engine.py | Apache-2.0 |
def __del__(self):
r"""Ensure server is cleaned up when object is deleted."""
self._cleanup_server()
try:
atexit.unregister(self._cleanup_server)
except Exception:
pass | Ensure server is cleaned up when object is deleted. | __del__ | python | hiyouga/LLaMA-Factory | src/llamafactory/chat/sglang_engine.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/chat/sglang_engine.py | Apache-2.0 |
def prepare_4d_attention_mask(attention_mask_with_indices: "torch.Tensor", dtype: "torch.dtype") -> "torch.Tensor":
r"""Expand 2d attention mask to 4d attention mask.
Expand the attention mask with indices from (batch_size, seq_len) to (batch_size, 1, seq_len, seq_len),
handle packed sequences and transfor... | Expand 2d attention mask to 4d attention mask.
Expand the attention mask with indices from (batch_size, seq_len) to (batch_size, 1, seq_len, seq_len),
handle packed sequences and transforms the mask to lower triangular form to prevent future peeking.
e.g.
```python
# input
[[1, 1, 2, 2, 2, 0]]... | prepare_4d_attention_mask | python | hiyouga/LLaMA-Factory | src/llamafactory/data/collator.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/collator.py | Apache-2.0 |
def __call__(self, features: list[dict[str, Any]]) -> dict[str, "torch.Tensor"]:
r"""Pad batched data to the longest sequence in the batch.
We generate 2 * n examples where the first n examples represent chosen examples and
the last n examples represent rejected examples.
"""
co... | Pad batched data to the longest sequence in the batch.
We generate 2 * n examples where the first n examples represent chosen examples and
the last n examples represent rejected examples.
| __call__ | python | hiyouga/LLaMA-Factory | src/llamafactory/data/collator.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/collator.py | Apache-2.0 |
def _find_medias(self, medias: Union["MediaType", list["MediaType"], None]) -> Optional[list["MediaType"]]:
r"""Optionally concatenate media path to media dir when loading from local disk."""
if medias is None:
return None
elif not isinstance(medias, list):
medias = [medi... | Optionally concatenate media path to media dir when loading from local disk. | _find_medias | python | hiyouga/LLaMA-Factory | src/llamafactory/data/converter.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/converter.py | Apache-2.0 |
def align_dataset(
dataset: Union["Dataset", "IterableDataset"],
dataset_attr: "DatasetAttr",
data_args: "DataArguments",
training_args: "Seq2SeqTrainingArguments",
) -> Union["Dataset", "IterableDataset"]:
r"""Align the dataset to a specific format.
Aligned dataset:
_prompt: [{"role": "use... | Align the dataset to a specific format.
Aligned dataset:
_prompt: [{"role": "user", "content": "..."}] * (2T - 1)
_response: [{"role": "assistant", "content": "..."}] * N (N > 1 for ranking dataset)
_system: "..."
_tools: "..."
_images: []
_videos: []
_audios: []
| align_dataset | python | hiyouga/LLaMA-Factory | src/llamafactory/data/converter.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/converter.py | Apache-2.0 |
def merge_dataset(
all_datasets: list[Union["Dataset", "IterableDataset"]], data_args: "DataArguments", seed: int
) -> Union["Dataset", "IterableDataset"]:
r"""Merge multiple datasets to a unified dataset."""
if len(all_datasets) == 1:
return all_datasets[0]
elif data_args.mix_strategy == "conc... | Merge multiple datasets to a unified dataset. | merge_dataset | python | hiyouga/LLaMA-Factory | src/llamafactory/data/data_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/data_utils.py | Apache-2.0 |
def split_dataset(
dataset: Optional[Union["Dataset", "IterableDataset"]],
eval_dataset: Optional[Union["Dataset", "IterableDataset", dict[str, "Dataset"]]],
data_args: "DataArguments",
seed: int,
) -> "DatasetDict":
r"""Split the dataset and returns a dataset dict containing train set and validatio... | Split the dataset and returns a dataset dict containing train set and validation set.
Support both map dataset and iterable dataset.
| split_dataset | python | hiyouga/LLaMA-Factory | src/llamafactory/data/data_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/data_utils.py | Apache-2.0 |
def get_dataset_module(dataset: Union["Dataset", "DatasetDict"]) -> "DatasetModule":
r"""Convert dataset or dataset dict to dataset module."""
dataset_module: DatasetModule = {}
if isinstance(dataset, DatasetDict): # dataset dict
if "train" in dataset:
dataset_module["train_dataset"] = ... | Convert dataset or dataset dict to dataset module. | get_dataset_module | python | hiyouga/LLaMA-Factory | src/llamafactory/data/data_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/data_utils.py | Apache-2.0 |
def setup_fs(path: str, anon: bool = False) -> "fsspec.AbstractFileSystem":
r"""Set up a filesystem object based on the path protocol."""
storage_options = {"anon": anon} if anon else {}
if path.startswith("s3://"):
fs = fsspec.filesystem("s3", **storage_options)
elif path.startswith(("gs://", "... | Set up a filesystem object based on the path protocol. | setup_fs | python | hiyouga/LLaMA-Factory | src/llamafactory/data/data_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/data_utils.py | Apache-2.0 |
def _read_json_with_fs(fs: "fsspec.AbstractFileSystem", path: str) -> list[Any]:
r"""Helper function to read JSON/JSONL files using fsspec."""
with fs.open(path, "r") as f:
if path.endswith(".jsonl"):
return [json.loads(line) for line in f if line.strip()]
else:
return js... | Helper function to read JSON/JSONL files using fsspec. | _read_json_with_fs | python | hiyouga/LLaMA-Factory | src/llamafactory/data/data_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/data_utils.py | Apache-2.0 |
def read_cloud_json(cloud_path: str) -> list[Any]:
r"""Read a JSON/JSONL file from cloud storage (S3 or GCS).
Args:
cloud_path: str
Cloud path in the format:
- 's3://bucket-name/file.json' for AWS S3
- 'gs://bucket-name/file.jsonl' or 'gcs://bucket-name/file.jsonl' f... | Read a JSON/JSONL file from cloud storage (S3 or GCS).
Args:
cloud_path: str
Cloud path in the format:
- 's3://bucket-name/file.json' for AWS S3
- 'gs://bucket-name/file.jsonl' or 'gcs://bucket-name/file.jsonl' for Google Cloud Storage
| read_cloud_json | python | hiyouga/LLaMA-Factory | src/llamafactory/data/data_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/data_utils.py | Apache-2.0 |
def _load_single_dataset(
dataset_attr: "DatasetAttr",
model_args: "ModelArguments",
data_args: "DataArguments",
training_args: "Seq2SeqTrainingArguments",
) -> Union["Dataset", "IterableDataset"]:
r"""Load a single dataset and aligns it to the standard format."""
logger.info_rank0(f"Loading dat... | Load a single dataset and aligns it to the standard format. | _load_single_dataset | python | hiyouga/LLaMA-Factory | src/llamafactory/data/loader.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/loader.py | Apache-2.0 |
def _get_merged_dataset(
dataset_names: Optional[list[str]],
model_args: "ModelArguments",
data_args: "DataArguments",
training_args: "Seq2SeqTrainingArguments",
stage: Literal["pt", "sft", "rm", "ppo", "kto"],
return_dict: bool = False,
) -> Optional[Union["Dataset", "IterableDataset", dict[str... | Return the merged datasets in the standard format. | _get_merged_dataset | python | hiyouga/LLaMA-Factory | src/llamafactory/data/loader.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/loader.py | Apache-2.0 |
def _get_preprocessed_dataset(
dataset: Optional[Union["Dataset", "IterableDataset"]],
data_args: "DataArguments",
training_args: "Seq2SeqTrainingArguments",
stage: Literal["pt", "sft", "rm", "ppo", "kto"],
template: "Template",
tokenizer: "PreTrainedTokenizer",
processor: Optional["Processo... | Preprocesses the dataset, including format checking and tokenization. | _get_preprocessed_dataset | python | hiyouga/LLaMA-Factory | src/llamafactory/data/loader.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/loader.py | Apache-2.0 |
def get_dataset(
template: "Template",
model_args: "ModelArguments",
data_args: "DataArguments",
training_args: "Seq2SeqTrainingArguments",
stage: Literal["pt", "sft", "rm", "ppo", "kto"],
tokenizer: "PreTrainedTokenizer",
processor: Optional["ProcessorMixin"] = None,
) -> "DatasetModule":
... | Get the train dataset and optionally gets the evaluation dataset. | get_dataset | python | hiyouga/LLaMA-Factory | src/llamafactory/data/loader.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/loader.py | Apache-2.0 |
def _get_paligemma_token_type_ids(imglens: list[int], seqlens: list[int], processor: "MMProcessor") -> list[list[int]]:
r"""Get paligemma token type ids for computing loss.
It is slightly different with the original token type ids where the prompt part is 0.
Returns:
batch_token_type_ids: shape (b... | Get paligemma token type ids for computing loss.
It is slightly different with the original token type ids where the prompt part is 0.
Returns:
batch_token_type_ids: shape (batch_size, seq_length)
| _get_paligemma_token_type_ids | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def _get_gemma3_token_type_ids(batch_ids: list[list[int]], processor: "MMProcessor"):
r"""Get gemma3 token type ids for computing loss.
Returns:
batch_token_type_ids: shape (batch_size, seq_length)
"""
image_token_id: int = getattr(processor, "image_token_id")
batch_token_type_ids = []
... | Get gemma3 token type ids for computing loss.
Returns:
batch_token_type_ids: shape (batch_size, seq_length)
| _get_gemma3_token_type_ids | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def _validate_input(
self,
processor: Optional["MMProcessor"],
images: list["ImageInput"],
videos: list["VideoInput"],
audios: list["AudioInput"],
) -> None:
r"""Validate if this model accepts the input modalities."""
image_processor: BaseImageProcessor = geta... | Validate if this model accepts the input modalities. | _validate_input | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def _validate_messages(
self,
messages: list[dict[str, str]],
images: list["ImageInput"],
videos: list["VideoInput"],
audios: list["AudioInput"],
):
r"""Validate if the number of images, videos and audios match the number of placeholders in messages."""
num_im... | Validate if the number of images, videos and audios match the number of placeholders in messages. | _validate_messages | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def _get_video_sample_indices(
self, video_stream: "Stream", video_fps: float, video_maxlen: int, **kwargs
) -> list[int]:
r"""Compute video sample indices according to fps."""
total_frames = video_stream.frames
if total_frames == 0: # infinite video
return np.linspace(0... | Compute video sample indices according to fps. | _get_video_sample_indices | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def _regularize_images(self, images: list["ImageInput"], **kwargs) -> dict[str, list["ImageObject"]]:
r"""Regularize images to avoid error. Including reading and pre-processing."""
results = []
for image in images:
if isinstance(image, (str, BinaryIO)):
image = Image.... | Regularize images to avoid error. Including reading and pre-processing. | _regularize_images | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def _regularize_videos(self, videos: list["VideoInput"], **kwargs) -> dict[str, list[list["ImageObject"]]]:
r"""Regularizes videos to avoid error. Including reading, resizing and converting."""
results = []
for video in videos:
frames: list[ImageObject] = []
if _check_vid... | Regularizes videos to avoid error. Including reading, resizing and converting. | _regularize_videos | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def _regularize_audios(
self, audios: list["AudioInput"], sampling_rate: float, **kwargs
) -> dict[str, Union[list["NDArray"], list[float]]]:
r"""Regularizes audios to avoid error. Including reading and resampling."""
results, sampling_rates = [], []
for audio in audios:
... | Regularizes audios to avoid error. Including reading and resampling. | _regularize_audios | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def _get_mm_inputs(
self,
images: list["ImageInput"],
videos: list["VideoInput"],
audios: list["AudioInput"],
processor: "MMProcessor",
imglens: Optional[list[int]] = None,
) -> dict[str, "torch.Tensor"]:
r"""Process visual inputs.
Returns: (llava and... | Process visual inputs.
Returns: (llava and paligemma)
pixel_values: tensor with shape (B, C, H, W)
Returns: (qwen2-vl)
pixel_values: tensor with shape (num_patches, patch_dim)
image_grid_thw: tensor with shape (num_images, 3), where the three numbers are time, width... | _get_mm_inputs | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def process_messages(
self,
messages: list[dict[str, str]],
images: list["ImageInput"],
videos: list["VideoInput"],
audios: list["AudioInput"],
processor: Optional["MMProcessor"],
) -> list[dict[str, str]]:
r"""Pre-process input messages before tokenization fo... | Pre-process input messages before tokenization for VLMs. | process_messages | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def process_token_ids(
self,
input_ids: list[int],
labels: Optional[list[int]],
images: list["ImageInput"],
videos: list["VideoInput"],
audios: list["AudioInput"],
tokenizer: "PreTrainedTokenizer",
processor: Optional["MMProcessor"],
) -> tuple[list[in... | Pre-process token ids after tokenization for VLMs. | process_token_ids | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def get_mm_inputs(
self,
images: list["ImageInput"],
videos: list["VideoInput"],
audios: list["AudioInput"],
imglens: list[int],
vidlens: list[int],
audlens: list[int],
batch_ids: list[list[int]],
processor: Optional["MMProcessor"],
) -> dict[s... | Build batched multimodal inputs for VLMs.
Arguments:
images: a list of image inputs, shape (num_images,)
videos: a list of video inputs, shape (num_videos,)
audios: a list of audio inputs, shape (num_audios,)
imglens: number of images in each sample, shape (batch... | get_mm_inputs | python | hiyouga/LLaMA-Factory | src/llamafactory/data/mm_plugin.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/mm_plugin.py | Apache-2.0 |
def get_dataset_list(dataset_names: Optional[list[str]], dataset_dir: str) -> list["DatasetAttr"]:
r"""Get the attributes of the datasets."""
if dataset_names is None:
dataset_names = []
if dataset_dir == "ONLINE":
dataset_info = None
else:
if dataset_dir.startswith("REMOTE:"):
... | Get the attributes of the datasets. | get_dataset_list | python | hiyouga/LLaMA-Factory | src/llamafactory/data/parser.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/parser.py | Apache-2.0 |
def encode_oneturn(
self,
tokenizer: "PreTrainedTokenizer",
messages: list[dict[str, str]],
system: Optional[str] = None,
tools: Optional[str] = None,
) -> tuple[list[int], list[int]]:
r"""Return a single pair of token ids representing prompt and response respectively... | Return a single pair of token ids representing prompt and response respectively. | encode_oneturn | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def encode_multiturn(
self,
tokenizer: "PreTrainedTokenizer",
messages: list[dict[str, str]],
system: Optional[str] = None,
tools: Optional[str] = None,
) -> list[tuple[list[int], list[int]]]:
r"""Return multiple pairs of token ids representing prompts and responses r... | Return multiple pairs of token ids representing prompts and responses respectively. | encode_multiturn | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def _encode(
self,
tokenizer: "PreTrainedTokenizer",
messages: list[dict[str, str]],
system: Optional[str],
tools: Optional[str],
) -> list[list[int]]:
r"""Encode formatted inputs to pairs of token ids.
Turn 0: prefix + system + query resp
Turn... | Encode formatted inputs to pairs of token ids.
Turn 0: prefix + system + query resp
Turn t: query resp.
| _encode | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def _add_or_replace_eos_token(tokenizer: "PreTrainedTokenizer", eos_token: str) -> None:
r"""Add or replace eos token to the tokenizer."""
if tokenizer.eos_token == eos_token:
return
is_added = tokenizer.eos_token_id is None
num_added_tokens = tokenizer.add_special_tokens({"... | Add or replace eos token to the tokenizer. | _add_or_replace_eos_token | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def fix_special_tokens(self, tokenizer: "PreTrainedTokenizer") -> None:
r"""Add eos token and pad token to the tokenizer."""
stop_words = self.stop_words
if self.replace_eos:
if not stop_words:
raise ValueError("Stop words are required to replace the EOS token.")
... | Add eos token and pad token to the tokenizer. | fix_special_tokens | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def fix_jinja_template(self, tokenizer: "PreTrainedTokenizer") -> None:
r"""Replace the jinja template in the tokenizer."""
if tokenizer.chat_template is None or self.replace_jinja_template:
try:
tokenizer.chat_template = self._get_jinja_template(tokenizer)
except... | Replace the jinja template in the tokenizer. | fix_jinja_template | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def get_ollama_modelfile(self, tokenizer: "PreTrainedTokenizer") -> str:
r"""Return the ollama modelfile.
TODO: support function calling.
"""
modelfile = "# ollama modelfile auto-generated by llamafactory\n\n"
modelfile += f'FROM .\n\nTEMPLATE """{self._get_ollama_template(token... | Return the ollama modelfile.
TODO: support function calling.
| get_ollama_modelfile | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def register_template(
name: str,
format_user: Optional["Formatter"] = None,
format_assistant: Optional["Formatter"] = None,
format_system: Optional["Formatter"] = None,
format_function: Optional["Formatter"] = None,
format_observation: Optional["Formatter"] = None,
format_tools: Optional["F... | Register a chat template.
To add the following chat template:
```
<s><user>user prompt here
<model>model response here</s>
<user>user prompt here
<model>model response here</s>
```
The corresponding code should be:
```
register_template(
name="custom",
format_us... | register_template | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def parse_template(tokenizer: "PreTrainedTokenizer") -> "Template":
r"""Extract a chat template from the tokenizer."""
def find_diff(short_str: str, long_str: str) -> str:
i, j = 0, 0
diff = ""
while i < len(short_str) and j < len(long_str):
if short_str[i] == long_str[j]:
... | Extract a chat template from the tokenizer. | parse_template | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def get_template_and_fix_tokenizer(tokenizer: "PreTrainedTokenizer", data_args: "DataArguments") -> "Template":
r"""Get chat template and fixes the tokenizer."""
if data_args.template is None:
if isinstance(tokenizer.chat_template, str):
logger.warning_rank0("`template` was not specified, tr... | Get chat template and fixes the tokenizer. | get_template_and_fix_tokenizer | python | hiyouga/LLaMA-Factory | src/llamafactory/data/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/template.py | Apache-2.0 |
def search_for_fit(numbers: list[int], capacity: int) -> int:
r"""Find the index of largest number that fits into the knapsack with the given capacity."""
index = bisect.bisect(numbers, capacity)
return -1 if index == 0 else (index - 1) | Find the index of largest number that fits into the knapsack with the given capacity. | search_for_fit | python | hiyouga/LLaMA-Factory | src/llamafactory/data/processor/processor_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/processor/processor_utils.py | Apache-2.0 |
def greedy_knapsack(numbers: list[int], capacity: int) -> list[list[int]]:
r"""Implement efficient greedy algorithm with binary search for the knapsack problem."""
numbers.sort() # sort numbers in ascending order for binary search
knapsacks = []
while numbers:
current_knapsack = []
rem... | Implement efficient greedy algorithm with binary search for the knapsack problem. | greedy_knapsack | python | hiyouga/LLaMA-Factory | src/llamafactory/data/processor/processor_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/processor/processor_utils.py | Apache-2.0 |
def infer_seqlen(source_len: int, target_len: int, cutoff_len: int) -> tuple[int, int]:
r"""Compute the real sequence length after truncation by the cutoff_len."""
if target_len * 2 < cutoff_len: # truncate source
max_target_len = cutoff_len
elif source_len * 2 < cutoff_len: # truncate target
... | Compute the real sequence length after truncation by the cutoff_len. | infer_seqlen | python | hiyouga/LLaMA-Factory | src/llamafactory/data/processor/processor_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/data/processor/processor_utils.py | Apache-2.0 |
def _parse_example(self, example: dict[str, str]) -> tuple[str, str]:
r"""Parse eval example.
input: a dict with keys {"question", "A", "B", "C", "D", "answer"}
output: a tuple of (prompt, response).
"""
candidates = [self.choice.format(choice=ch, content=example[ch]) for ch in ... | Parse eval example.
input: a dict with keys {"question", "A", "B", "C", "D", "answer"}
output: a tuple of (prompt, response).
| _parse_example | python | hiyouga/LLaMA-Factory | src/llamafactory/eval/template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/eval/template.py | Apache-2.0 |
def _configure_library_root_logger() -> None:
r"""Configure root logger using a stdout stream handler with an explicit format."""
global _default_handler
with _thread_lock:
if _default_handler: # already configured
return
formatter = logging.Formatter(
fmt="[%(leve... | Configure root logger using a stdout stream handler with an explicit format. | _configure_library_root_logger | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/logging.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/logging.py | Apache-2.0 |
def get_logger(name: Optional[str] = None) -> "_Logger":
r"""Return a logger with the specified name. It it not supposed to be accessed externally."""
if name is None:
name = _get_library_name()
_configure_library_root_logger()
return logging.getLogger(name) | Return a logger with the specified name. It it not supposed to be accessed externally. | get_logger | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/logging.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/logging.py | Apache-2.0 |
def check_dependencies() -> None:
r"""Check the version of the required packages."""
check_version(
"transformers>=4.45.0,<=4.52.4,!=4.46.0,!=4.46.1,!=4.46.2,!=4.46.3,!=4.47.0,!=4.47.1,!=4.48.0,!=4.52.0"
)
check_version("datasets>=2.16.0,<=3.6.0")
check_version("accelerate>=0.34.0,<=1.7.0")
... | Check the version of the required packages. | check_dependencies | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def count_parameters(model: "torch.nn.Module") -> tuple[int, int]:
r"""Return the number of trainable parameters and number of all parameters in the model."""
trainable_params, all_param = 0, 0
for param in model.parameters():
num_params = param.numel()
# if using DS Zero 3 and the weights a... | Return the number of trainable parameters and number of all parameters in the model. | count_parameters | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def get_device_count() -> int:
r"""Get the number of available devices."""
if is_torch_xpu_available():
return torch.xpu.device_count()
elif is_torch_npu_available():
return torch.npu.device_count()
elif is_torch_mps_available():
return torch.mps.device_count()
elif is_torch_... | Get the number of available devices. | get_device_count | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def get_logits_processor() -> "LogitsProcessorList":
r"""Get logits processor that removes NaN and Inf logits."""
logits_processor = LogitsProcessorList()
logits_processor.append(InfNanRemoveLogitsProcessor())
return logits_processor | Get logits processor that removes NaN and Inf logits. | get_logits_processor | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def get_peak_memory() -> tuple[int, int]:
r"""Get the peak memory usage for the current device (in Bytes)."""
if is_torch_xpu_available():
return torch.xpu.max_memory_allocated(), torch.xpu.max_memory_reserved()
elif is_torch_npu_available():
return torch.npu.max_memory_allocated(), torch.np... | Get the peak memory usage for the current device (in Bytes). | get_peak_memory | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def infer_optim_dtype(model_dtype: "torch.dtype") -> "torch.dtype":
r"""Infer the optimal dtype according to the model_dtype and device compatibility."""
if _is_bf16_available and model_dtype == torch.bfloat16:
return torch.bfloat16
elif _is_fp16_available:
return torch.float16
else:
... | Infer the optimal dtype according to the model_dtype and device compatibility. | infer_optim_dtype | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def is_accelerator_available() -> bool:
r"""Check if the accelerator is available."""
return (
is_torch_xpu_available() or is_torch_npu_available() or is_torch_mps_available() or is_torch_cuda_available()
) | Check if the accelerator is available. | is_accelerator_available | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def numpify(inputs: Union["NDArray", "torch.Tensor"]) -> "NDArray":
r"""Cast a torch tensor or a numpy array to a numpy array."""
if isinstance(inputs, torch.Tensor):
inputs = inputs.cpu()
if inputs.dtype == torch.bfloat16: # numpy does not support bfloat16 until 1.21.4
inputs = inp... | Cast a torch tensor or a numpy array to a numpy array. | numpify | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def skip_check_imports() -> None:
r"""Avoid flash attention import error in custom model files."""
if not is_env_enabled("FORCE_CHECK_IMPORTS"):
transformers.dynamic_module_utils.check_imports = get_relative_imports | Avoid flash attention import error in custom model files. | skip_check_imports | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def find_available_port() -> int:
r"""Find an available port on the local machine."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 0))
port = sock.getsockname()[1]
sock.close()
return port | Find an available port on the local machine. | find_available_port | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def fix_proxy(ipv6_enabled: bool = False) -> None:
r"""Fix proxy settings for gradio ui."""
os.environ["no_proxy"] = "localhost,127.0.0.1,0.0.0.0"
if ipv6_enabled:
for name in ("http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY"):
os.environ.pop(name, None) | Fix proxy settings for gradio ui. | fix_proxy | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/misc.py | Apache-2.0 |
def plot_loss(save_dictionary: str, keys: list[str] = ["loss"]) -> None:
r"""Plot loss curves and saves the image."""
plt.switch_backend("agg")
with open(os.path.join(save_dictionary, TRAINER_STATE_NAME), encoding="utf-8") as f:
data = json.load(f)
for key in keys:
steps, metrics = [], ... | Plot loss curves and saves the image. | plot_loss | python | hiyouga/LLaMA-Factory | src/llamafactory/extras/ploting.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/extras/ploting.py | Apache-2.0 |
def read_args(args: Optional[Union[dict[str, Any], list[str]]] = None) -> Union[dict[str, Any], list[str]]:
r"""Get arguments from the command line or a config file."""
if args is not None:
return args
if sys.argv[1].endswith(".yaml") or sys.argv[1].endswith(".yml"):
override_config = Omega... | Get arguments from the command line or a config file. | read_args | python | hiyouga/LLaMA-Factory | src/llamafactory/hparams/parser.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/hparams/parser.py | Apache-2.0 |
def init_adapter(
config: "PretrainedConfig",
model: "PreTrainedModel",
model_args: "ModelArguments",
finetuning_args: "FinetuningArguments",
is_trainable: bool,
) -> "PreTrainedModel":
r"""Initialize the adapters.
Support full-parameter, freeze and LoRA training.
Note that the trainab... | Initialize the adapters.
Support full-parameter, freeze and LoRA training.
Note that the trainable parameters must be cast to float32.
| init_adapter | python | hiyouga/LLaMA-Factory | src/llamafactory/model/adapter.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/adapter.py | Apache-2.0 |
def _get_init_kwargs(model_args: "ModelArguments") -> dict[str, Any]:
r"""Get arguments to load config/tokenizer/model.
Note: including inplace operation of model_args.
"""
skip_check_imports()
model_args.model_name_or_path = try_download_model_from_other_hub(model_args)
return {
"trust... | Get arguments to load config/tokenizer/model.
Note: including inplace operation of model_args.
| _get_init_kwargs | python | hiyouga/LLaMA-Factory | src/llamafactory/model/loader.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/loader.py | Apache-2.0 |
def load_tokenizer(model_args: "ModelArguments") -> "TokenizerModule":
r"""Load pretrained tokenizer and optionally loads processor.
Note: including inplace operation of model_args.
"""
init_kwargs = _get_init_kwargs(model_args)
try:
tokenizer = AutoTokenizer.from_pretrained(
mo... | Load pretrained tokenizer and optionally loads processor.
Note: including inplace operation of model_args.
| load_tokenizer | python | hiyouga/LLaMA-Factory | src/llamafactory/model/loader.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/loader.py | Apache-2.0 |
def get_custom_gradient_checkpointing_func(gradient_checkpointing_func: Callable) -> Callable:
r"""Only applies gradient checkpointing to trainable layers."""
@wraps(gradient_checkpointing_func, assigned=WRAPPER_ASSIGNMENTS + ("__self__",))
def custom_gradient_checkpointing_func(func: Callable, *args: Unio... | Only applies gradient checkpointing to trainable layers. | get_custom_gradient_checkpointing_func | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/checkpointing.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/checkpointing.py | Apache-2.0 |
def _gradient_checkpointing_enable(
self: "PreTrainedModel",
gradient_checkpointing_kwargs: Optional[dict[str, Any]] = None,
use_unsloth_gc: bool = False,
) -> None:
r"""Activates gradient checkpointing for the current model.
Modification of the original method to enable gradient checkpointing for ... | Activates gradient checkpointing for the current model.
Modification of the original method to enable gradient checkpointing for block-wise optimizer.
| _gradient_checkpointing_enable | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/checkpointing.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/checkpointing.py | Apache-2.0 |
def prepare_model_for_training(model: "PreTrainedModel", model_args: "ModelArguments") -> None:
r"""Prepare the model before training.
Include:
(1) cast the layernorm in fp32
(2) make output embedding layer require grads
(3) add the upcasting of the lm_head in fp32.
"""
if model_args.upcast... | Prepare the model before training.
Include:
(1) cast the layernorm in fp32
(2) make output embedding layer require grads
(3) add the upcasting of the lm_head in fp32.
| prepare_model_for_training | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/checkpointing.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/checkpointing.py | Apache-2.0 |
def find_all_linear_modules(model: "PreTrainedModel", freeze_vision_tower: bool) -> list[str]:
r"""Find all available modules to apply LoRA, GaLore or APOLLO."""
model_type = getattr(model.config, "model_type", None)
forbidden_modules = {"lm_head"}
if model_type == "chatglm":
forbidden_modules.a... | Find all available modules to apply LoRA, GaLore or APOLLO. | find_all_linear_modules | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/misc.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/misc.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.