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 find_expanded_modules(model: "PreTrainedModel", target_modules: list[str], num_layer_trainable: int) -> list[str]:
r"""Find the modules in the expanded blocks to apply lora."""
num_layers = getattr(model.config, "num_hidden_layers", None)
if not num_layers:
raise ValueError("Model was not suppor... | Find the modules in the expanded blocks to apply lora. | find_expanded_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 |
def add_z3_leaf_module(model: "PreTrainedModel") -> None:
r"""Set module as a leaf module to skip partitioning in deepspeed zero3."""
if not is_deepspeed_zero3_enabled():
return
model_type = getattr(model.config, "model_type", None)
if model_type == "dbrx":
from transformers.models.dbrx... | Set module as a leaf module to skip partitioning in deepspeed zero3. | add_z3_leaf_module | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/moe.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/moe.py | Apache-2.0 |
def get_seqlens_in_batch(attention_mask: "torch.Tensor") -> "torch.Tensor":
r"""Get the sequnce lengths in the current batch.
e.g.
```python
# input
[
[1, 1, 2, 2, 2, 0],
[1, 2, 2, 3, 3, 3],
]
# output
[2, 3, 1, 2, 3]
```
"""
bsz = attention_mask.size(0)
... | Get the sequnce lengths in the current batch.
e.g.
```python
# input
[
[1, 1, 2, 2, 2, 0],
[1, 2, 2, 3, 3, 3],
]
# output
[2, 3, 1, 2, 3]
```
| get_seqlens_in_batch | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/packing.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/packing.py | Apache-2.0 |
def get_unpad_data(attention_mask: "torch.Tensor") -> tuple["torch.Tensor", "torch.Tensor", int]:
r"""Prepare the indices and seqlens for flash attn varlen function.
Returns:
indices: indices of non-masked tokens from the flattened sequence.
cu_seqlens: the cumulative sequence lengths in the cu... | Prepare the indices and seqlens for flash attn varlen function.
Returns:
indices: indices of non-masked tokens from the flattened sequence.
cu_seqlens: the cumulative sequence lengths in the current batch, always starts from 0.
max_seqlen_in_batch: the largest seqlen in the current batch.
... | get_unpad_data | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/packing.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/packing.py | Apache-2.0 |
def _get_quantization_dataset(tokenizer: "PreTrainedTokenizer", model_args: "ModelArguments") -> list[dict[str, Any]]:
r"""Prepare the tokenized dataset to perform AutoGPTQ. Do not use tensor output for JSON serialization."""
if os.path.isfile(model_args.export_quantization_dataset):
data_path = FILEEXT... | Prepare the tokenized dataset to perform AutoGPTQ. Do not use tensor output for JSON serialization. | _get_quantization_dataset | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/quantization.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/quantization.py | Apache-2.0 |
def configure_quantization(
config: "PretrainedConfig",
tokenizer: "PreTrainedTokenizer",
model_args: "ModelArguments",
init_kwargs: dict[str, Any],
) -> None:
r"""Priority: PTQ-quantized (train/infer) > AutoGPTQ (export) > On-the-fly quantization (train/infer)."""
if getattr(config, "quantizati... | Priority: PTQ-quantized (train/infer) > AutoGPTQ (export) > On-the-fly quantization (train/infer). | configure_quantization | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/quantization.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/quantization.py | Apache-2.0 |
def load_unsloth_pretrained_model(
config: "PretrainedConfig", model_args: "ModelArguments", finetuning_args: "FinetuningArguments"
) -> Optional["PreTrainedModel"]:
r"""Optionally load pretrained model with unsloth. Used in training."""
from unsloth import FastLanguageModel # type: ignore
unsloth_kwa... | Optionally load pretrained model with unsloth. Used in training. | load_unsloth_pretrained_model | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/unsloth.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/unsloth.py | Apache-2.0 |
def get_unsloth_peft_model(
model: "PreTrainedModel", model_args: "ModelArguments", peft_kwargs: dict[str, Any]
) -> "PreTrainedModel":
r"""Get the peft model for the pretrained model with unsloth. Used in training."""
from unsloth import FastLanguageModel # type: ignore
unsloth_peft_kwargs = {
... | Get the peft model for the pretrained model with unsloth. Used in training. | get_unsloth_peft_model | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/unsloth.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/unsloth.py | Apache-2.0 |
def load_unsloth_peft_model(
config: "PretrainedConfig", model_args: "ModelArguments", is_trainable: bool
) -> "PreTrainedModel":
r"""Load peft model with unsloth. Used in both training and inference."""
from unsloth import FastLanguageModel # type: ignore
unsloth_kwargs = _get_unsloth_kwargs(config, ... | Load peft model with unsloth. Used in both training and inference. | load_unsloth_peft_model | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/unsloth.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/unsloth.py | Apache-2.0 |
def load_valuehead_params(path_or_repo_id: str, model_args: "ModelArguments") -> dict[str, torch.Tensor]:
r"""Load value head parameters from Hugging Face Hub or local disk.
Returns: dict with keys `v_head.summary.weight` and `v_head.summary.bias`.
"""
kwargs = {"path_or_repo_id": path_or_repo_id, "cac... | Load value head parameters from Hugging Face Hub or local disk.
Returns: dict with keys `v_head.summary.weight` and `v_head.summary.bias`.
| load_valuehead_params | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/valuehead.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/valuehead.py | Apache-2.0 |
def _register_composite_model(
model_type: str,
projector_key: Optional[str] = None,
vision_model_keys: Optional[list[str]] = None,
language_model_keys: Optional[list[str]] = None,
lora_conflict_keys: Optional[list[str]] = None,
):
r"""Register a new composite model.
Args:
model_typ... | Register a new composite model.
Args:
model_type: model type
projector_key: multi_modal_projector
vision_model_keys: vision_tower
language_model_keys: language_model
lora_conflict_keys: None
| _register_composite_model | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/visual.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/visual.py | Apache-2.0 |
def autocast_projector_dtype(model: "PreTrainedModel", model_args: "ModelArguments") -> None:
r"""Cast projector output to half precision for fine-tuning quantized VLMs."""
def _mm_projector_forward_post_hook(
module: "torch.nn.Module", args: tuple["torch.Tensor"], output: "torch.Tensor"
) -> "torc... | Cast projector output to half precision for fine-tuning quantized VLMs. | autocast_projector_dtype | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/visual.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/visual.py | Apache-2.0 |
def get_forbidden_modules(config: "PretrainedConfig", finetuning_args: "FinetuningArguments") -> set[str]:
r"""Freeze vision tower and language model for VLM full/freeze tuning."""
model_type = getattr(config, "model_type", None)
forbidden_modules = set()
if model_type in COMPOSITE_MODELS:
if fi... | Freeze vision tower and language model for VLM full/freeze tuning. | get_forbidden_modules | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/visual.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/visual.py | Apache-2.0 |
def patch_target_modules(
model: "PreTrainedModel", finetuning_args: "FinetuningArguments", target_modules: list[str]
) -> list[str]:
r"""Freeze vision tower for VLM LoRA tuning."""
model_type = getattr(model.config, "model_type", None)
if model_type in COMPOSITE_MODELS:
forbidden_modules = get_... | Freeze vision tower for VLM LoRA tuning. | patch_target_modules | python | hiyouga/LLaMA-Factory | src/llamafactory/model/model_utils/visual.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/model/model_utils/visual.py | Apache-2.0 |
def zeropower_via_newtonschulz5(G: "torch.Tensor", steps: int) -> "torch.Tensor":
"""Newton-Schulz iteration to compute the zeroth power / orthogonalization of G.
We opt to use a quintic iteration whose coefficients are selected to maximize the slope at zero.
For the purpose of minimizing steps, it turns o... | Newton-Schulz iteration to compute the zeroth power / orthogonalization of G.
We opt to use a quintic iteration whose coefficients are selected to maximize the slope at zero.
For the purpose of minimizing steps, it turns out to be empirically effective to keep increasing
the slope at zero even beyond the p... | zeropower_via_newtonschulz5 | python | hiyouga/LLaMA-Factory | src/llamafactory/third_party/muon/muon.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/third_party/muon/muon.py | Apache-2.0 |
def fix_valuehead_checkpoint(
model: "AutoModelForCausalLMWithValueHead", output_dir: str, safe_serialization: bool
) -> None:
r"""Fix the valuehead checkpoint files.
The model is already unwrapped.
There are three cases:
1. full tuning without ds_zero3: state_dict = {"model.layers.*": ..., "v_hea... | Fix the valuehead checkpoint files.
The model is already unwrapped.
There are three cases:
1. full tuning without ds_zero3: state_dict = {"model.layers.*": ..., "v_head.summary.*": ...}
2. lora tuning without ds_zero3: state_dict = {"v_head.summary.*": ...}
3. under deepspeed zero3: state_dict = {... | fix_valuehead_checkpoint | python | hiyouga/LLaMA-Factory | src/llamafactory/train/callbacks.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/callbacks.py | Apache-2.0 |
def create_ref_model(
model_args: "ModelArguments", finetuning_args: "FinetuningArguments", add_valuehead: bool = False
) -> Optional[Union["PreTrainedModel", "AutoModelForCausalLMWithValueHead"]]:
r"""Create reference model for PPO/DPO training. Evaluation mode is not supported.
The valuehead parameter is... | Create reference model for PPO/DPO training. Evaluation mode is not supported.
The valuehead parameter is randomly initialized since it is useless for PPO training.
| create_ref_model | python | hiyouga/LLaMA-Factory | src/llamafactory/train/trainer_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/trainer_utils.py | Apache-2.0 |
def create_reward_model(
model: "AutoModelForCausalLMWithValueHead", model_args: "ModelArguments", finetuning_args: "FinetuningArguments"
) -> Optional["AutoModelForCausalLMWithValueHead"]:
r"""Create reward model for PPO training."""
if finetuning_args.reward_model_type == "api":
assert finetuning_... | Create reward model for PPO training. | create_reward_model | python | hiyouga/LLaMA-Factory | src/llamafactory/train/trainer_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/trainer_utils.py | Apache-2.0 |
def _get_decay_parameter_names(model: "PreTrainedModel") -> list[str]:
r"""Return a list of names of parameters with weight decay. (weights in non-layernorm layers)."""
decay_parameters = get_parameter_names(model, ALL_LAYERNORM_LAYERS)
decay_parameters = [name for name in decay_parameters if "bias" not in ... | Return a list of names of parameters with weight decay. (weights in non-layernorm layers). | _get_decay_parameter_names | python | hiyouga/LLaMA-Factory | src/llamafactory/train/trainer_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/trainer_utils.py | Apache-2.0 |
def get_batch_logps(
logits: "torch.Tensor", labels: "torch.Tensor", label_pad_token_id: int = IGNORE_INDEX
) -> tuple["torch.Tensor", "torch.Tensor"]:
r"""Compute the log probabilities of the given labels under the given logits.
Returns:
logps: A tensor of shape (batch_size,) containing the sum of... | Compute the log probabilities of the given labels under the given logits.
Returns:
logps: A tensor of shape (batch_size,) containing the sum of log probabilities.
valid_length: A tensor of shape (batch_size,) containing the number of non-masked tokens.
| get_batch_logps | python | hiyouga/LLaMA-Factory | src/llamafactory/train/trainer_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/trainer_utils.py | Apache-2.0 |
def nested_detach(
tensors: Union["torch.Tensor", list["torch.Tensor"], tuple["torch.Tensor"], dict[str, "torch.Tensor"]],
clone: bool = False,
):
r"""Detach `tensors` (even if it's a nested list/tuple/dict of tensors)."""
if isinstance(tensors, (list, tuple)):
return type(tensors)(nested_detach... | Detach `tensors` (even if it's a nested list/tuple/dict of tensors). | nested_detach | python | hiyouga/LLaMA-Factory | src/llamafactory/train/trainer_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/trainer_utils.py | Apache-2.0 |
def odds_ratio_loss(self, chosen_logps: "torch.Tensor", rejected_logps: "torch.Tensor") -> "torch.Tensor":
r"""Compute ORPO's odds ratio (OR) loss for batched log probabilities of the policy model."""
log_odds = (chosen_logps - rejected_logps) - (
torch.log1p(-torch.exp(chosen_logps)) - torc... | Compute ORPO's odds ratio (OR) loss for batched log probabilities of the policy model. | odds_ratio_loss | python | hiyouga/LLaMA-Factory | src/llamafactory/train/dpo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/dpo/trainer.py | Apache-2.0 |
def simpo_loss(self, chosen_logps: "torch.Tensor", rejected_logps: "torch.Tensor") -> "torch.Tensor":
r"""Compute SimPO loss for batched log probabilities of the policy model."""
pi_logratios = chosen_logps - rejected_logps
gamma_logratios = self.simpo_gamma / self.beta
logits = pi_logra... | Compute SimPO loss for batched log probabilities of the policy model. | simpo_loss | python | hiyouga/LLaMA-Factory | src/llamafactory/train/dpo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/dpo/trainer.py | Apache-2.0 |
def concatenated_forward(
self, model: "PreTrainedModel", batch: dict[str, "torch.Tensor"]
) -> tuple["torch.Tensor", "torch.Tensor", "torch.Tensor", "torch.Tensor", "torch.Tensor"]:
r"""Compute the sum log probabilities of the labels under given logits if loss_type is not IPO, ORPO or SimPO.
... | Compute the sum log probabilities of the labels under given logits if loss_type is not IPO, ORPO or SimPO.
Otherwise the average log probabilities.
| concatenated_forward | python | hiyouga/LLaMA-Factory | src/llamafactory/train/dpo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/dpo/trainer.py | Apache-2.0 |
def compute_reference_log_probs(
self, model: "PreTrainedModel", batch: dict[str, "torch.Tensor"]
) -> tuple[Optional["torch.Tensor"], Optional["torch.Tensor"]]:
r"""Compute log probabilities of the reference model."""
if not self.finetuning_args.use_ref_model:
return None, None
... | Compute log probabilities of the reference model. | compute_reference_log_probs | python | hiyouga/LLaMA-Factory | src/llamafactory/train/dpo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/dpo/trainer.py | Apache-2.0 |
def compute_loss(
self, model: "PreTrainedModel", inputs: dict[str, "torch.Tensor"], return_outputs: bool = False, **kwargs
) -> Union["torch.Tensor", tuple["torch.Tensor", list["torch.Tensor"]]]:
r"""Subclass and override to accept extra kwargs."""
return super().compute_loss(model, inputs,... | Subclass and override to accept extra kwargs. | compute_loss | python | hiyouga/LLaMA-Factory | src/llamafactory/train/dpo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/dpo/trainer.py | Apache-2.0 |
def log(self, logs: dict[str, float], *args, **kwargs) -> None:
r"""Log `logs` on the various objects watching training, including stored metrics."""
# logs either has "loss" or "eval_loss"
train_eval = "train" if "loss" in logs else "eval"
# Add averaged stored metrics to logs
k... | Log `logs` on the various objects watching training, including stored metrics. | log | python | hiyouga/LLaMA-Factory | src/llamafactory/train/dpo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/dpo/trainer.py | Apache-2.0 |
def _get_train_sampler(self, *args, **kwargs) -> Optional["torch.utils.data.Sampler"]:
r"""Replace the sequential sampler of KTO Trainer created by trl with the random sampler."""
if self.finetuning_args.disable_shuffling:
return torch.utils.data.SequentialSampler(self.train_dataset)
... | Replace the sequential sampler of KTO Trainer created by trl with the random sampler. | _get_train_sampler | python | hiyouga/LLaMA-Factory | src/llamafactory/train/kto/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/kto/trainer.py | Apache-2.0 |
def forward(
self, model: "PreTrainedModel", batch: dict[str, "torch.Tensor"], prefix: Literal["", "kl_"] = ""
) -> tuple["torch.Tensor", "torch.Tensor", "torch.Tensor"]:
r"""Run forward pass and computes the log probabilities."""
batch = nested_detach(batch, clone=True) # avoid error
... | Run forward pass and computes the log probabilities. | forward | python | hiyouga/LLaMA-Factory | src/llamafactory/train/kto/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/kto/trainer.py | Apache-2.0 |
def get_rewards_from_server(server_url: str, messages: list[str]) -> list["torch.Tensor"]:
r"""Get reward scores from the API server."""
headers = {"Content-Type": "application/json"}
payload = {"model": "model", "messages": messages}
response = requests.post(server_url, json=payload, headers=headers)
... | Get reward scores from the API server. | get_rewards_from_server | python | hiyouga/LLaMA-Factory | src/llamafactory/train/ppo/ppo_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/ppo/ppo_utils.py | Apache-2.0 |
def replace_model(model: "AutoModelForCausalLMWithValueHead", target: Literal["default", "reward"]) -> None:
r"""Replace the default/reward modules in the model. The model is already unwrapped."""
v_head_layer = model.v_head.summary
if is_deepspeed_zero3_enabled():
import deepspeed # type: ignore
... | Replace the default/reward modules in the model. The model is already unwrapped. | replace_model | python | hiyouga/LLaMA-Factory | src/llamafactory/train/ppo/ppo_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/ppo/ppo_utils.py | Apache-2.0 |
def dump_layernorm(model: "PreTrainedModel") -> dict[str, "torch.Tensor"]:
r"""Dump the layernorm parameters in the model. The model is already unwrapped (and gathered)."""
layer_norm_params = {}
for name, param in model.named_parameters():
if param.data.dtype == torch.float32:
layer_nor... | Dump the layernorm parameters in the model. The model is already unwrapped (and gathered). | dump_layernorm | python | hiyouga/LLaMA-Factory | src/llamafactory/train/ppo/ppo_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/ppo/ppo_utils.py | Apache-2.0 |
def restore_layernorm(model: "PreTrainedModel", layernorm_params: Optional[dict[str, "torch.Tensor"]] = None) -> None:
r"""Restore the layernorm parameters in the model. The model is already unwrapped (and gathered)."""
for name, param in model.named_parameters():
if name in layernorm_params:
... | Restore the layernorm parameters in the model. The model is already unwrapped (and gathered). | restore_layernorm | python | hiyouga/LLaMA-Factory | src/llamafactory/train/ppo/ppo_utils.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/ppo/ppo_utils.py | Apache-2.0 |
def ppo_train(self, resume_from_checkpoint: Optional[str] = None) -> None:
r"""Implement training loop for the PPO stage, like _inner_training_loop() in Huggingface's Trainer."""
if resume_from_checkpoint is not None:
raise ValueError("`resume_from_checkpoint` will be supported in the future... | Implement training loop for the PPO stage, like _inner_training_loop() in Huggingface's Trainer. | ppo_train | python | hiyouga/LLaMA-Factory | src/llamafactory/train/ppo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/ppo/trainer.py | Apache-2.0 |
def get_rewards(
self,
queries: list["torch.Tensor"],
responses: list["torch.Tensor"],
) -> list["torch.Tensor"]:
r"""Compute scores using given reward model.
Both inputs and outputs are put on CPU.
"""
if self.finetuning_args.reward_model_type == "api":
... | Compute scores using given reward model.
Both inputs and outputs are put on CPU.
| get_rewards | python | hiyouga/LLaMA-Factory | src/llamafactory/train/ppo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/ppo/trainer.py | Apache-2.0 |
def batched_forward_pass(
self,
model: "AutoModelForCausalLMWithValueHead",
queries: "torch.Tensor",
responses: "torch.Tensor",
model_inputs: dict[str, Any],
return_logits: bool = False,
response_masks: Optional["torch.Tensor"] = None,
) -> tuple["torch.Tensor... | Calculate model outputs in multiple batches.
Subclass and override to inject custom behavior.
| batched_forward_pass | python | hiyouga/LLaMA-Factory | src/llamafactory/train/ppo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/ppo/trainer.py | Apache-2.0 |
def save_model(self, output_dir: Optional[str] = None) -> None:
r"""Save model checkpoint.
Subclass and override to inject custom behavior.
"""
if output_dir is None:
output_dir = self.args.output_dir
if self.is_fsdp_enabled or self.is_deepspeed_enabled:
... | Save model checkpoint.
Subclass and override to inject custom behavior.
| save_model | python | hiyouga/LLaMA-Factory | src/llamafactory/train/ppo/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/ppo/trainer.py | Apache-2.0 |
def compute_loss(
self, model: "PreTrainedModel", inputs: dict[str, "torch.Tensor"], return_outputs: bool = False, **kwargs
) -> Union["torch.Tensor", tuple["torch.Tensor", list["torch.Tensor"]]]:
r"""Compute pairwise loss. The first n examples are chosen and the last n examples are rejected.
... | Compute pairwise loss. The first n examples are chosen and the last n examples are rejected.
Subclass and override to inject custom behavior.
Note that the first element will be removed from the output tuple.
See: https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/traine... | compute_loss | python | hiyouga/LLaMA-Factory | src/llamafactory/train/rm/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/rm/trainer.py | Apache-2.0 |
def save_predictions(self, predict_results: "PredictionOutput") -> None:
r"""Save model predictions to `output_dir`.
A custom behavior that not contained in Seq2SeqTrainer.
"""
if not self.is_world_process_zero():
return
output_prediction_file = os.path.join(self.ar... | Save model predictions to `output_dir`.
A custom behavior that not contained in Seq2SeqTrainer.
| save_predictions | python | hiyouga/LLaMA-Factory | src/llamafactory/train/rm/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/rm/trainer.py | Apache-2.0 |
def eval_logit_processor(logits: "torch.Tensor", labels: "torch.Tensor") -> "torch.Tensor":
r"""Compute the token with the largest likelihood to reduce memory footprint."""
if isinstance(logits, (list, tuple)):
if logits[0].dim() == 3: # (batch_size, seq_len, vocab_size)
logits = logits[0]
... | Compute the token with the largest likelihood to reduce memory footprint. | eval_logit_processor | python | hiyouga/LLaMA-Factory | src/llamafactory/train/sft/metric.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/sft/metric.py | Apache-2.0 |
def prediction_step(
self,
model: "torch.nn.Module",
inputs: dict[str, Union["torch.Tensor", Any]],
prediction_loss_only: bool,
ignore_keys: Optional[list[str]] = None,
**gen_kwargs,
) -> tuple[Optional[float], Optional["torch.Tensor"], Optional["torch.Tensor"]]:
... | Remove the prompt part in the generated tokens.
Subclass and override to inject custom behavior.
| prediction_step | python | hiyouga/LLaMA-Factory | src/llamafactory/train/sft/trainer.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/train/sft/trainer.py | Apache-2.0 |
def _format_response(text: str, lang: str, escape_html: bool, thought_words: tuple[str, str]) -> str:
r"""Post-process the response text.
Based on: https://huggingface.co/spaces/Lyte/DeepSeek-R1-Distill-Qwen-1.5B-Demo-GGUF/blob/main/app.py
"""
if thought_words[0] not in text:
return _escape_htm... | Post-process the response text.
Based on: https://huggingface.co/spaces/Lyte/DeepSeek-R1-Distill-Qwen-1.5B-Demo-GGUF/blob/main/app.py
| _format_response | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/chatter.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/chatter.py | Apache-2.0 |
def append(
chatbot: list[dict[str, str]],
messages: list[dict[str, str]],
role: str,
query: str,
escape_html: bool,
) -> tuple[list[dict[str, str]], list[dict[str, str]], str]:
r"""Add the user input to chatbot.
Inputs: infer.chatbot, infer.messages, infer.r... | Add the user input to chatbot.
Inputs: infer.chatbot, infer.messages, infer.role, infer.query, infer.escape_html
Output: infer.chatbot, infer.messages, infer.query
| append | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/chatter.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/chatter.py | Apache-2.0 |
def stream(
self,
chatbot: list[dict[str, str]],
messages: list[dict[str, str]],
lang: str,
system: str,
tools: str,
image: Optional[Any],
video: Optional[Any],
audio: Optional[Any],
max_new_tokens: int,
top_p: float,
temper... | Generate output text in stream.
Inputs: infer.chatbot, infer.messages, infer.system, infer.tools, infer.image, infer.video, ...
Output: infer.chatbot, infer.messages
| stream | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/chatter.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/chatter.py | Apache-2.0 |
def abort_process(pid: int) -> None:
r"""Abort the processes recursively in a bottom-up way."""
try:
children = Process(pid).children()
if children:
for child in children:
abort_process(child.pid)
os.kill(pid, signal.SIGABRT)
except Exception:
pas... | Abort the processes recursively in a bottom-up way. | abort_process | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/common.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/common.py | Apache-2.0 |
def get_save_dir(*paths: str) -> os.PathLike:
r"""Get the path to saved model checkpoints."""
if os.path.sep in paths[-1]:
logger.warning_rank0("Found complex path, some features may be not available.")
return paths[-1]
paths = (path.replace(" ", "").strip() for path in paths)
return os... | Get the path to saved model checkpoints. | get_save_dir | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/common.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/common.py | Apache-2.0 |
def get_model_path(model_name: str) -> str:
r"""Get the model path according to the model name."""
user_config = load_config()
path_dict: dict[DownloadSource, str] = SUPPORTED_MODELS.get(model_name, defaultdict(str))
model_path = user_config["path_dict"].get(model_name, "") or path_dict.get(DownloadSour... | Get the model path according to the model name. | get_model_path | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/common.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/common.py | Apache-2.0 |
def load_args(config_path: str) -> Optional[dict[str, Any]]:
r"""Load the training configuration from config path."""
try:
with open(config_path, encoding="utf-8") as f:
return safe_load(f)
except Exception:
return None | Load the training configuration from config path. | load_args | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/common.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/common.py | Apache-2.0 |
def _clean_cmd(args: dict[str, Any]) -> dict[str, Any]:
r"""Remove args with NoneType or False or empty string value."""
no_skip_keys = [
"packing",
"enable_thinking",
"use_reentrant_gc",
"double_quantization",
"freeze_vision_tower",
"freeze_multi_modal_projector"... | Remove args with NoneType or False or empty string value. | _clean_cmd | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/common.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/common.py | Apache-2.0 |
def save_cmd(args: dict[str, Any]) -> str:
r"""Save CLI commands to launch training."""
output_dir = args["output_dir"]
os.makedirs(output_dir, exist_ok=True)
with open(os.path.join(output_dir, TRAINING_ARGS), "w", encoding="utf-8") as f:
safe_dump(_clean_cmd(args), f)
return os.path.join(o... | Save CLI commands to launch training. | save_cmd | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/common.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/common.py | Apache-2.0 |
def calculate_pixels(pixels: str) -> int:
r"""Calculate the number of pixels from the expression."""
if "*" in pixels:
return int(pixels.split("*")[0]) * int(pixels.split("*")[1])
else:
return int(pixels) | Calculate the number of pixels from the expression. | calculate_pixels | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/common.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/common.py | Apache-2.0 |
def create_ds_config() -> None:
r"""Create deepspeed config in the current directory."""
os.makedirs(DEFAULT_CACHE_DIR, exist_ok=True)
ds_config = {
"train_batch_size": "auto",
"train_micro_batch_size_per_gpu": "auto",
"gradient_accumulation_steps": "auto",
"gradient_clipping... | Create deepspeed config in the current directory. | create_ds_config | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/common.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/common.py | Apache-2.0 |
def can_quantize(finetuning_type: str) -> "gr.Dropdown":
r"""Judge if the quantization is available in this finetuning type.
Inputs: top.finetuning_type
Outputs: top.quantization_bit
"""
if finetuning_type not in PEFT_METHODS:
return gr.Dropdown(value="none", interactive=False)
else:
... | Judge if the quantization is available in this finetuning type.
Inputs: top.finetuning_type
Outputs: top.quantization_bit
| can_quantize | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/control.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/control.py | Apache-2.0 |
def can_quantize_to(quantization_method: str) -> "gr.Dropdown":
r"""Get the available quantization bits.
Inputs: top.quantization_method
Outputs: top.quantization_bit
"""
if quantization_method == QuantizationMethod.BNB:
available_bits = ["none", "8", "4"]
elif quantization_method == Qu... | Get the available quantization bits.
Inputs: top.quantization_method
Outputs: top.quantization_bit
| can_quantize_to | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/control.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/control.py | Apache-2.0 |
def get_trainer_info(lang: str, output_path: os.PathLike, do_train: bool) -> tuple[str, "gr.Slider", dict[str, Any]]:
r"""Get training infomation for monitor.
If do_train is True:
Inputs: top.lang, train.output_path
Outputs: train.output_box, train.progress_bar, train.loss_viewer, train.swanlab... | Get training infomation for monitor.
If do_train is True:
Inputs: top.lang, train.output_path
Outputs: train.output_box, train.progress_bar, train.loss_viewer, train.swanlab_link
If do_train is False:
Inputs: top.lang, eval.output_path
Outputs: eval.output_box, eval.progress_bar... | get_trainer_info | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/control.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/control.py | Apache-2.0 |
def list_checkpoints(model_name: str, finetuning_type: str) -> "gr.Dropdown":
r"""List all available checkpoints.
Inputs: top.model_name, top.finetuning_type
Outputs: top.checkpoint_path
"""
checkpoints = []
if model_name:
save_dir = get_save_dir(model_name, finetuning_type)
if ... | List all available checkpoints.
Inputs: top.model_name, top.finetuning_type
Outputs: top.checkpoint_path
| list_checkpoints | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/control.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/control.py | Apache-2.0 |
def list_config_paths(current_time: str) -> "gr.Dropdown":
r"""List all the saved configuration files.
Inputs: train.current_time
Outputs: train.config_path
"""
config_files = [f"{current_time}.yaml"]
if os.path.isdir(DEFAULT_CONFIG_DIR):
for file_name in os.listdir(DEFAULT_CONFIG_DIR):... | List all the saved configuration files.
Inputs: train.current_time
Outputs: train.config_path
| list_config_paths | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/control.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/control.py | Apache-2.0 |
def list_datasets(dataset_dir: str = None, training_stage: str = list(TRAINING_STAGES.keys())[0]) -> "gr.Dropdown":
r"""List all available datasets in the dataset dir for the training stage.
Inputs: *.dataset_dir, *.training_stage
Outputs: *.dataset
"""
dataset_info = load_dataset_info(dataset_dir ... | List all available datasets in the dataset dir for the training stage.
Inputs: *.dataset_dir, *.training_stage
Outputs: *.dataset
| list_datasets | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/control.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/control.py | Apache-2.0 |
def list_output_dirs(model_name: Optional[str], finetuning_type: str, current_time: str) -> "gr.Dropdown":
r"""List all the directories that can resume from.
Inputs: top.model_name, top.finetuning_type, train.current_time
Outputs: train.output_dir
"""
output_dirs = [f"train_{current_time}"]
if ... | List all the directories that can resume from.
Inputs: top.model_name, top.finetuning_type, train.current_time
Outputs: train.output_dir
| list_output_dirs | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/control.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/control.py | Apache-2.0 |
def _update_component(self, input_dict: dict[str, dict[str, Any]]) -> dict["Component", "Component"]:
r"""Update gradio components according to the (elem_id, properties) mapping."""
output_dict: dict[Component, Component] = {}
for elem_id, elem_attr in input_dict.items():
elem = self... | Update gradio components according to the (elem_id, properties) mapping. | _update_component | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/engine.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/engine.py | Apache-2.0 |
def resume(self):
r"""Get the initial value of gradio components and restores training status if necessary."""
user_config = load_config() if not self.demo_mode else {} # do not use config in demo mode
lang = user_config.get("lang", None) or "en"
init_dict = {"top.lang": {"value": lang}... | Get the initial value of gradio components and restores training status if necessary. | resume | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/engine.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/engine.py | Apache-2.0 |
def change_lang(self, lang: str):
r"""Update the displayed language of gradio components."""
return {
elem: elem.__class__(**LOCALES[elem_name][lang])
for elem_name, elem in self.manager.get_elem_iter()
if elem_name in LOCALES
} | Update the displayed language of gradio components. | change_lang | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/engine.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/engine.py | Apache-2.0 |
def get_elem_iter(self) -> Generator[tuple[str, "Component"], None, None]:
r"""Return an iterator over all elements with their names."""
for elem_id, elem in self._id_to_elem.items():
yield elem_id.split(".")[-1], elem | Return an iterator over all elements with their names. | get_elem_iter | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/manager.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/manager.py | Apache-2.0 |
def get_base_elems(self) -> set["Component"]:
r"""Get the base elements that are commonly used."""
return {
self._id_to_elem["top.lang"],
self._id_to_elem["top.model_name"],
self._id_to_elem["top.model_path"],
self._id_to_elem["top.finetuning_type"],
... | Get the base elements that are commonly used. | get_base_elems | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/manager.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/manager.py | Apache-2.0 |
def _finalize(self, lang: str, finish_info: str) -> str:
r"""Clean the cached memory and resets the runner."""
finish_info = ALERTS["info_aborted"][lang] if self.aborted else finish_info
gr.Info(finish_info)
self.trainer = None
self.aborted = False
self.running = False
... | Clean the cached memory and resets the runner. | _finalize | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/runner.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/runner.py | Apache-2.0 |
def _parse_train_args(self, data: dict["Component", Any]) -> dict[str, Any]:
r"""Build and validate the training arguments."""
get = lambda elem_id: data[self.manager.get_elem_by_id(elem_id)]
model_name, finetuning_type = get("top.model_name"), get("top.finetuning_type")
user_config = lo... | Build and validate the training arguments. | _parse_train_args | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/runner.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/runner.py | Apache-2.0 |
def _parse_eval_args(self, data: dict["Component", Any]) -> dict[str, Any]:
r"""Build and validate the evaluation arguments."""
get = lambda elem_id: data[self.manager.get_elem_by_id(elem_id)]
model_name, finetuning_type = get("top.model_name"), get("top.finetuning_type")
user_config = l... | Build and validate the evaluation arguments. | _parse_eval_args | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/runner.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/runner.py | Apache-2.0 |
def _build_config_dict(self, data: dict["Component", Any]) -> dict[str, Any]:
r"""Build a dictionary containing the current training configuration."""
config_dict = {}
skip_ids = ["top.lang", "top.model_path", "train.output_dir", "train.config_path"]
for elem, value in data.items():
... | Build a dictionary containing the current training configuration. | _build_config_dict | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/runner.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/runner.py | Apache-2.0 |
def monitor(self):
r"""Monitorgit the training progress and logs."""
self.aborted = False
self.running = True
get = lambda elem_id: self.running_data[self.manager.get_elem_by_id(elem_id)]
lang, model_name, finetuning_type = get("top.lang"), get("top.model_name"), get("top.finetu... | Monitorgit the training progress and logs. | monitor | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/runner.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/runner.py | Apache-2.0 |
def save_args(self, data):
r"""Save the training configuration to config path."""
output_box = self.manager.get_elem_by_id("train.output_box")
error = self._initialize(data, do_train=True, from_preview=True)
if error:
gr.Warning(error)
return {output_box: error}
... | Save the training configuration to config path. | save_args | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/runner.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/runner.py | Apache-2.0 |
def check_output_dir(self, lang: str, model_name: str, finetuning_type: str, output_dir: str):
r"""Restore the training status if output_dir exists."""
output_box = self.manager.get_elem_by_id("train.output_box")
output_dict: dict[Component, Any] = {output_box: LOCALES["output_box"][lang]["value... | Restore the training status if output_dir exists. | check_output_dir | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/runner.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/runner.py | Apache-2.0 |
def check_json_schema(text: str, lang: str) -> None:
r"""Check if the json schema is valid."""
try:
tools = json.loads(text)
if tools:
assert isinstance(tools, list)
for tool in tools:
if "name" not in tool:
raise NotImplementedError("N... | Check if the json schema is valid. | check_json_schema | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/components/chatbot.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/components/chatbot.py | Apache-2.0 |
def can_preview(dataset_dir: str, dataset: list) -> "gr.Button":
r"""Check if the dataset is a local dataset."""
try:
with open(os.path.join(dataset_dir, DATA_CONFIG), encoding="utf-8") as f:
dataset_info = json.load(f)
except Exception:
return gr.Button(interactive=False)
i... | Check if the dataset is a local dataset. | can_preview | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/components/data.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/components/data.py | Apache-2.0 |
def get_preview(dataset_dir: str, dataset: list, page_index: int) -> tuple[int, list, "gr.Column"]:
r"""Get the preview samples from the dataset."""
with open(os.path.join(dataset_dir, DATA_CONFIG), encoding="utf-8") as f:
dataset_info = json.load(f)
data_path = os.path.join(dataset_dir, dataset_in... | Get the preview samples from the dataset. | get_preview | python | hiyouga/LLaMA-Factory | src/llamafactory/webui/components/data.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/src/llamafactory/webui/components/data.py | Apache-2.0 |
def _check_tokenization(
tokenizer: "PreTrainedTokenizer", batch_input_ids: list[list[int]], batch_text: list[str]
) -> None:
r"""Check token ids and texts.
encode(text) == token_ids
decode(token_ids) == text
"""
for input_ids, text in zip(batch_input_ids, batch_text):
assert tokenizer.... | Check token ids and texts.
encode(text) == token_ids
decode(token_ids) == text
| _check_tokenization | python | hiyouga/LLaMA-Factory | tests/data/test_template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/tests/data/test_template.py | Apache-2.0 |
def _check_template(
model_id: str,
template_name: str,
prompt_str: str,
answer_str: str,
use_fast: bool,
messages: list[dict[str, str]] = MESSAGES,
) -> None:
r"""Check template.
Args:
model_id: the model id on hugging face hub.
template_name: the template name.
... | Check template.
Args:
model_id: the model id on hugging face hub.
template_name: the template name.
prompt_str: the string corresponding to the prompt part.
answer_str: the string corresponding to the answer part.
use_fast: whether to use fast tokenizer.
messages: th... | _check_template | python | hiyouga/LLaMA-Factory | tests/data/test_template.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/tests/data/test_template.py | Apache-2.0 |
def test_chat():
r"""Test the SGLang engine's basic chat functionality."""
chat_model = ChatModel(INFER_ARGS)
response = chat_model.chat(MESSAGES)[0]
# TODO: Change to EXPECTED_RESPONSE
print(response.response_text) | Test the SGLang engine's basic chat functionality. | test_chat | python | hiyouga/LLaMA-Factory | tests/e2e/test_sglang.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/tests/e2e/test_sglang.py | Apache-2.0 |
def test_stream_chat():
r"""Test the SGLang engine's streaming chat functionality."""
chat_model = ChatModel(INFER_ARGS)
response = ""
for token in chat_model.stream_chat(MESSAGES):
response += token
print("Complete response:", response)
assert response, "Should receive a non-empty res... | Test the SGLang engine's streaming chat functionality. | test_stream_chat | python | hiyouga/LLaMA-Factory | tests/e2e/test_sglang.py | https://github.com/hiyouga/LLaMA-Factory/blob/master/tests/e2e/test_sglang.py | Apache-2.0 |
def get(self, request):
"""
User list api / Get user by id
"""
user_id = request.GET.get("id")
if user_id:
try:
user = User.objects.get(id=user_id)
except User.DoesNotExist:
return self.error("User does not exist")
... |
User list api / Get user by id
| get | python | QingdaoU/OnlineJudge | account/views/admin.py | https://github.com/QingdaoU/OnlineJudge/blob/master/account/views/admin.py | MIT |
def post(self, request):
"""
check username or email is duplicate
"""
data = request.data
# True means already exist.
result = {
"username": False,
"email": False
}
if data.get("username"):
result["username"] = User.obje... |
check username or email is duplicate
| post | python | QingdaoU/OnlineJudge | account/views/oj.py | https://github.com/QingdaoU/OnlineJudge/blob/master/account/views/oj.py | MIT |
def get(self, request):
"""
get announcement list / get one announcement
"""
announcement_id = request.GET.get("id")
if announcement_id:
try:
announcement = Announcement.objects.get(id=announcement_id)
return self.success(AnnouncementSe... |
get announcement list / get one announcement
| get | python | QingdaoU/OnlineJudge | announcement/views/admin.py | https://github.com/QingdaoU/OnlineJudge/blob/master/announcement/views/admin.py | MIT |
def validate_serializer(serializer):
"""
@validate_serializer(TestSerializer)
def post(self, request):
return self.success(request.data)
"""
def validate(view_method):
@functools.wraps(view_method)
def handle(*args, **kwargs):
self = args[0]
request = ... |
@validate_serializer(TestSerializer)
def post(self, request):
return self.success(request.data)
| validate_serializer | python | QingdaoU/OnlineJudge | utils/api/api.py | https://github.com/QingdaoU/OnlineJudge/blob/master/utils/api/api.py | MIT |
def delete_unjustified_issues(accounts, monitors):
""" Allows us to delete unjustified issues. """
monitor_names = _parse_tech_names(monitors)
try:
_parse_accounts(accounts)
except KeyError as e:
app.logger.error("The passed in account: {} does not exist in Security Monkey's database.".f... | Allows us to delete unjustified issues. | delete_unjustified_issues | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def export_environment_summary(output_file):
""" Save the Auditor.OBJECT_STORE as a JSON file. """
from security_monkey.auditor import Auditor
from collections import defaultdict
# Build the Environment Summary
Auditor._load_object_store()
# Convert sets to lists so we can serialize with JSON
... | Save the Auditor.OBJECT_STORE as a JSON file. | export_environment_summary | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def backup_config_to_json(accounts, monitors, outputfolder):
""" Saves the most current item revisions to a json file. """
monitor_names = _parse_tech_names(monitors)
try:
account_names = _parse_accounts(accounts)
except KeyError as e:
app.logger.error("The passed in account: {} does not... | Saves the most current item revisions to a json file. | backup_config_to_json | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def clear_expired_exceptions():
"""
Clears out the exception logs table of all exception entries that have expired past the TTL.
:return:
"""
app.logger.info("Clearing out exceptions that have an expired TTL...")
clear_old_exceptions()
app.logger.info("Completed clearing out exceptions that ... |
Clears out the exception logs table of all exception entries that have expired past the TTL.
:return:
| clear_expired_exceptions | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def amazon_accounts():
""" Pre-populates standard AWS owned accounts """
import json
from security_monkey.datastore import Account, AccountType
data = json.load(open("data/aws_accounts.json", 'r'))
app.logger.info('Adding / updating Amazon owned accounts')
try:
account_type_result = Ac... | Pre-populates standard AWS owned accounts | amazon_accounts | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def disable_accounts(accounts):
""" Bulk disables one or more accounts """
try:
account_names = _parse_accounts(accounts)
except KeyError as e:
app.logger.error("The passed in account: {} does not exist in Security Monkey's database.".format(e.message))
return -1
bulk_disable_ac... | Bulk disables one or more accounts | disable_accounts | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def enable_accounts(accounts):
""" Bulk enables one or more accounts """
try:
account_names = _parse_accounts(accounts)
except KeyError as e:
app.logger.error("The passed in account: {} does not exist in Security Monkey's database.".format(e.message))
return -1
bulk_enable_accou... | Bulk enables one or more accounts | enable_accounts | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def add_override_score(tech_name, method, auditor, score, disabled, pattern_scores):
"""
Adds an audit disable/override scores
:param tech_name: technology index
:param method: the neme of the auditor method to override
:param auditor: The class name of the auditor containing the check method
:p... |
Adds an audit disable/override scores
:param tech_name: technology index
:param method: the neme of the auditor method to override
:param auditor: The class name of the auditor containing the check method
:param score: The default override score to assign to the check method issue
:param disabl... | add_override_score | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def add_override_scores(file_name, field_mappings):
"""
Refreshes the audit disable/override scores from a csv file. Old scores not in
the csv will be removed.
:param file_name: path to the csv file
:param field_mappings: Comma separated list of mappings of known types to csv file
headers. Ex.... |
Refreshes the audit disable/override scores from a csv file. Old scores not in
the csv will be removed.
:param file_name: path to the csv file
:param field_mappings: Comma separated list of mappings of known types to csv file
headers. Ex. 'tech=Tech Name,score=default score'
| add_override_scores | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def _parse_accounts(account_str, active=True):
"""Parse the account ID or name. This will raise a KeyError if it can't find it."""
if account_str == 'all':
accounts = Account.query.filter(Account.third_party == False).filter(Account.active == active).all()
accounts = [account.name for account in... | Parse the account ID or name. This will raise a KeyError if it can't find it. | _parse_accounts | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def fetch_aws_canonical_ids(override):
"""
Adds S3 canonical IDs in for all AWS accounts in SM.
"""
app.logger.info("[ ] Fetching S3 canonical IDs for all AWS accounts being monitored by Security Monkey.")
# Get all the active AWS accounts:
accounts = Account.query.filter(Account.active == True... |
Adds S3 canonical IDs in for all AWS accounts in SM.
| fetch_aws_canonical_ids | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def sync_swag(owner, bucket_name, bucket_prefix, bucket_region, account_type, spinnaker):
"""Use the SWAG client to sync SWAG accounts to Security Monkey."""
from security_monkey.account_manager import account_registry
swag_opts = {
'swag.type': 's3',
'swag.bucket_name': bucket_name,
... | Use the SWAG client to sync SWAG accounts to Security Monkey. | sync_swag | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def sync_networks(bucket_name, input_filename, authoritative):
"""Imports a JSON file of networks to the Security Monkey whitelist."""
if bucket_name:
import boto3
s3 = boto3.client('s3')
response = s3.get_object(
Bucket=bucket_name,
Key=input_filename,
)
... | Imports a JSON file of networks to the Security Monkey whitelist. | sync_networks | python | Netflix/security_monkey | manage.py | https://github.com/Netflix/security_monkey/blob/master/manage.py | Apache-2.0 |
def env_to_bool(input):
"""
Must change String from environment variable into Boolean
defaults to True
"""
if isinstance(input, str):
if input in ('False', 'false'):
return False
else:
return True
else:
return input |
Must change String from environment variable into Boolean
defaults to True
| env_to_bool | python | Netflix/security_monkey | env-config/config-docker.py | https://github.com/Netflix/security_monkey/blob/master/env-config/config-docker.py | Apache-2.0 |
def upgrade():
"""This revision is going to expand the hash database fields from `varchar(32)` to `varchar(64)`. Due to the usage of DeepHash.
Note: This is going to result in all change items getting re-updated as the hashes are going to be different.
"""
op.alter_column('item', 'latest_revision_comple... | This revision is going to expand the hash database fields from `varchar(32)` to `varchar(64)`. Due to the usage of DeepHash.
Note: This is going to result in all change items getting re-updated as the hashes are going to be different.
| upgrade | python | Netflix/security_monkey | migrations/versions/15e39d43395f_.py | https://github.com/Netflix/security_monkey/blob/master/migrations/versions/15e39d43395f_.py | Apache-2.0 |
def upgrade():
"""
Need to detect duplicate items.
This needs to be done by looking for all items with the same: region, name, tech_id, account_id.
With these items, pick the one that has the bigger latest_revision_id and delete the others.
:return:
"""
bind = op.get_bind()
session = Ses... |
Need to detect duplicate items.
This needs to be done by looking for all items with the same: region, name, tech_id, account_id.
With these items, pick the one that has the bigger latest_revision_id and delete the others.
:return:
| upgrade | python | Netflix/security_monkey | migrations/versions/7c54b06e227b_.py | https://github.com/Netflix/security_monkey/blob/master/migrations/versions/7c54b06e227b_.py | Apache-2.0 |
def sub_list(l):
"""
Recursively walk a datastructrue sorting any lists along the way.
:param l: list
:return: sorted list, where any child lists are also sorted.
"""
r = []
for i in l:
if type(i) in prims:
r.append(i)
elif type(i) is list:
r.append(... |
Recursively walk a datastructrue sorting any lists along the way.
:param l: list
:return: sorted list, where any child lists are also sorted.
| sub_list | python | Netflix/security_monkey | migrations/versions/bfb550a500ab_.py | https://github.com/Netflix/security_monkey/blob/master/migrations/versions/bfb550a500ab_.py | Apache-2.0 |
def sub_dict(d):
"""
Recursively walk a datastructure sorting any lists along the way.
:param d: dict
:return: dict where any lists, even those buried deep in the structure, have been sorted.
"""
r = {}
for k in d:
if type(d[k]) in prims:
r[k] = d[k]
elif type(d[... |
Recursively walk a datastructure sorting any lists along the way.
:param d: dict
:return: dict where any lists, even those buried deep in the structure, have been sorted.
| sub_dict | python | Netflix/security_monkey | migrations/versions/bfb550a500ab_.py | https://github.com/Netflix/security_monkey/blob/master/migrations/versions/bfb550a500ab_.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.