Transformers documentation
Monkey patching (tính năng thử nghiệm)
Monkey patching (tính năng thử nghiệm)
Monkey patching cho phép bạn thay thế các thành phần của model trên toàn cục mà không cần sửa đổi mã nguồn model gốc. Sau khi được đăng ký, các patch sẽ được áp dụng tự động khi tải bất kỳ model nào bằng from_pretrained() hoặc ~PreTrainedModel.from_config. Điều này cho phép bạn tái cấu trúc model cho các yêu cầu cụ thể như khả năng tương thích với quantization, áp dụng các tối ưu hóa, hoặc thử nghiệm các biến thể kiến trúc.
Monkey patching nên được coi là giải pháp cuối cùng khi bạn cần thay đổi bố cục và cấu trúc của một module và/hoặc trọng số của nó. Đối với nhiều nhu cầu tùy chỉnh và tối ưu hóa, hãy thử sử dụng Attention interface, Experts interface, hoặc Kernels registry thay thế. Chỉ sử dụng monkey patching khi bạn cần những thay đổi về cấu trúc mà không thể đạt được chỉ bằng các cài đặt forward tùy chỉnh (ví dụ: để tương thích với thư viện lượng tử hóa, hợp nhất các lớp, hoặc thử nghiệm kiến trúc).
Bắt đầu nhanh
Dưới đây là một ví dụ đơn giản cho thấy cách thay thế một thành phần của mô hình:
from transformers import AutoModelForCausalLM
from transformers.models.llama.modeling_llama import LlamaAttention
from transformers.monkey_patching import register_patch_mapping
# Define your replacement class (must inherit from nn.Module)
class CustomLlamaAttention(LlamaAttention):
def forward(self, *args, **kwargs):
# Your custom implementation
print("Using custom attention!")
return super().forward(*args, **kwargs)
# Register the patch globally (only applies to transformers modeling modules)
register_patch_mapping(mapping={"LlamaAttention": CustomLlamaAttention})
# Load a model - the patch is automatically applied during initialization
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
# All LlamaAttention layers in the model are now CustomLlamaAttention instances
print(type(model.model.layers[0].self_attn)) # <class '__main__.CustomLlamaAttention'>Cách hoạt động
Monkey patches hoạt động thông qua một quy trình hai bước:
Đăng ký: Gọi
register_patch_mappingđể thêm các ánh xạ vào một bộ đăng ký toàn cục.Ứng dụng: Các bản vá được áp dụng tự động trong quá trình khởi tạo mô hình:
from_pretrained/from_config: Các patch được áp dụng tự động thông qua một context manager nội bộ. Không cần thực hiện thêm thao tác nào!- Xây dựng thủ công (ví dụ:
Model(config)): Bạn phải sử dụng trình quản lý ngữ cảnhapply_patchesmột cách thủ công.
Một khi các patch được đăng ký, chúng sẽ tồn tại và ảnh hưởng đến tất cả các lần tải mô hình tiếp theo cho đến khi bạn xóa chúng bằng clear_patch_mapping.
Hạn chế quan trọng:
- Chỉ các lớp trong các module modeling của
transformersmới được phép vá (ví dụ:LlamaAttention,LlamaMLP). - Các khóa ánh xạ có thể là tên lớp chính xác hoặc các mẫu biểu thức chính quy (xem Khớp mẫu bên dưới).
Đăng ký toàn cục
Sử dụng register_patch_mapping để đăng ký các ánh xạ toàn cục:
from transformers.monkey_patching import register_patch_mapping
# Register a single patch
register_patch_mapping(
mapping={"Qwen2MoeExperts": SequentialExperts}
)
# Register multiple patches at once
register_patch_mapping(
mapping={
"Qwen2MoeExperts": SequentialExperts,
"Qwen2MoeAttention": CustomAttention,
},
# Overwrite existing patches if they exist
overwrite=True,
)Ghép mẫu
Bạn có thể sử dụng biểu thức chính quy để khớp nhiều lớp với một mẫu duy nhất:
from transformers.monkey_patching import register_patch_mapping
# Match all classes containing "Attention"
register_patch_mapping(
mapping={".*Attention": CustomAttention}
)
# More examples
register_patch_mapping(
mapping={
".*MoeExperts$": CustomExperts, # Ends with "MoeExperts"
"^Llama\\d+Attention$": CustomAttention, # Llama2Attention, Llama3Attention, etc.
}
)Quan trọng: Khớp chính xác có độ ưu tiên cao hơn so với mẫu. Nếu bạn đăng ký cả "LlamaAttention" và ".*Attention", các lớp có tên LlamaAttention sẽ sử dụng thay thế khớp chính xác, trong khi các lớp khớp khác sẽ sử dụng thay thế khớp mẫu.
Mẫu Regex có thể âm thầm làm hỏng mô hình. Một mẫu rộng như
".*Attention"sẽ khớp với mọi lớp có tên chứa “Attention” — bao gồm cả các lớp container bọc quanh phần attention mà bạn thực sự muốn thay thế. Ví dụ, BERT có ba lớp liên quan đến attention:BertSelfAttentionvàBertCrossAttention(các triển khai attention bên trong) vàBertAttention(một module bên ngoài chứa một trong những lớp bên trong đó). Việc vá cả ba lớp bằng cùng một lớp attention tùy chỉnh sẽ tạo ra một mô hình bị hỏng vì lớp bên ngoàiBertAttentionkhông còn bọc lớp bên trong nữa — nó chính là một lớp bên trong, loại bỏ các module con dự kiến nhưselfvàoutput. Hãy ưu tiên các mẫu hẹp (ví dụ:".*SelfAttention$") hoặc tên lớp chính xác để tránh các khớp không mong muốn.
Để hủy đăng ký các bản vá, hãy sử dụng unregister_patch_mapping:
from transformers.monkey_patching import unregister_patch_mapping
# Unregister a single patch (use exact name or pattern from registration)
unregister_patch_mapping(keys=["Qwen2MoeExperts"])
# Unregister multiple patches at once
unregister_patch_mapping(keys=["Qwen2MoeExperts", "Qwen2MoeAttention"])
# Unregister a pattern
unregister_patch_mapping(keys=[".*Attention"])Để xóa tất cả các patch đã đăng ký, hãy sử dụng clear_patch_mapping:
from transformers.monkey_patching import clear_patch_mapping
clear_patch_mapping()Để xem các patch đã được đăng ký hiện tại, hãy sử dụng get_patch_mapping:
from transformers.monkey_patching import get_patch_mapping
current_patches = get_patch_mapping()
print(current_patches)Xây dựng mô hình thủ công
Trình quản lý ngữ cảnh apply_patches chỉ cần thiết khi bạn xây dựng các mô hình thủ công (ví dụ: Model(config)) mà không sử dụng from_pretrained hoặc from_config:
from transformers import LlamaModel, LlamaConfig
from transformers.monkey_patching import register_patch_mapping, apply_patches
# Register patch globally
register_patch_mapping(mapping={"LlamaAttention": CustomAttention})
# For manual construction, you need the context manager
with apply_patches():
model = LlamaModel(LlamaConfig()) # Uses CustomAttention
# Without the context manager, manual construction uses original classes
model = LlamaModel(LlamaConfig()) # Uses LlamaAttention
# But from_pretrained and from_config will always apply registered patches
model = LlamaModel.from_pretrained("meta-llama/Llama-3.2-1B") # Uses CustomAttentionGhi chú quan trọng
Xử lý trọng số: Monkey patching chỉ thay thế các lớp, không thay thế trọng số. Nếu lớp đã được vá của bạn có bố cục trọng số khác, bạn sẽ cần xử lý chuyển đổi trọng số riêng biệt để đảm bảo tương thích với trọng số được huấn luyện trước. Xem Ví dụ hoàn chỉnh bên dưới để biết cách kết hợp monkey patch với ánh xạ chuyển đổi trọng số.
Tác dụng toàn cục: Các patch được đăng ký bằng
register_patch_mappingsẽ được áp dụng toàn cục cho tất cả các model được nạp sau khi đăng ký. Luôn sử dụngclear_patch_mappingđể dọn dẹp khi hoàn tất, đặc biệt là trong các bài kiểm thử, notebook hoặc ứng dụng chạy dài.Định dạng lớp: API tự động kiểm tra xem các lớp thay thế có phải là lớp con của
nn.Modulehay không. Nếu bạn truyền vào một lớp không hợp lệ, bạn sẽ nhận được thông báo lỗi rõ ràng.An toàn luồng: Tất cả các thao tác vá đều an toàn cho luồng. Bạn có thể đăng ký, hủy đăng ký và áp dụng các bản vá từ nhiều luồng một cách an toàn.
Khớp hành vi: Khi sử dụng tên lớp chính xác, chúng phải khớp hoàn toàn với tên lớp gốc như xuất hiện trong mã nguồn của mô hình (phân biệt chữ hoa chữ thường). Khi sử dụng mẫu regex, chúng được khớp với tên lớp bằng
re.search().
Xử lý sự cố
Patch của tôi không được áp dụng
Kiểm tra tên lớp hoặc mẫu: Đảm bảo tên lớp hoặc mẫu trong ánh xạ của bạn là chính xác:
# For exact names - must match exactly (case-sensitive)
register_patch_mapping(mapping={"LlamaAttention": CustomAttention})
# For patterns - use valid regex
register_patch_mapping(mapping={".*Attention": CustomAttention})Xác nhận đăng ký: Sử dụng get_patch_mapping để xác nhận ánh xạ của bạn đã được đăng ký:
print(get_patch_mapping())
# Shows all registered mappings: {'LlamaAttention': <class 'CustomAttention'>, '.*MLP': <class 'CustomMLP'>}Kiểm tra nguồn mô hình: Tìm tên lớp chính xác trong mã nguồn của mô hình:
from transformers.models.llama import modeling_llama
print(dir(modeling_llama)) # Look for the class nameLàm thế nào để biết patch của tôi có đang hoạt động không?
Kiểm tra mô hình đã tải để xác minh bản vá:
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
# Check the type of a specific module
print(type(model.model.layers[0].self_attn)) # Should show your custom class
# Or iterate through all modules
for name, module in model.named_modules():
if 'attention' in name.lower():
print(f"{name}: {type(module)}")Lỗi không khớp hình dạng trọng số
Nếu lớp đã vá của bạn có các hình dạng trọng số khác nhau, hãy đăng ký một quy tắc chuyển đổi trọng số:
from transformers.conversion_mapping import register_checkpoint_conversion_mapping, WeightConverter
from transformers.monkey_patching import register_patch_mapping
register_patch_mapping(
mapping={
"LlamaAttention": LlamaFusedAttention,
}
)
register_checkpoint_conversion_mapping(
model_type_or_class_name="llama",
mapping=[
WeightConverter(
source_patterns=["q_proj", "k_proj", "v_proj"],
target_patterns=["qkv_proj"],
operations=[
Concatenate(dim=0),
],
)
],
overwrite=True,
)Dọn dẹp các bản vá
Luôn dọn dẹp các bản vá khi hoàn tất để tránh ảnh hưởng đến các mã khác:
from transformers.monkey_patching import register_patch_mapping, clear_patch_mapping
try:
register_patch_mapping(mapping={"LlamaAttention": CustomAttention})
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
# ... use model ...
finally:
clear_patch_mapping() # Always clean upVí dụ hoàn chỉnh
Dưới đây là một ví dụ toàn diện cho thấy cách tái cấu trúc cả các module chuyên gia và module chú ý trong một mô hình Mixture-of-Experts (qwen2_moe) để tối ưu hóa và tương thích với lượng tử hóa. Ví dụ này minh họa:
- Tạo các lớp thay thế tùy chỉnh duy trì cùng một giao diện
- Đăng ký các monkey patch cho nhiều thành phần
- Xử lý chuyển đổi trọng số cho cấu trúc mới
from typing import Unpack
import torch
import torch.nn as nn
from transformers import AutoModelForCausalLM, Concatenate, WeightConverter
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache
from transformers.conversion_mapping import register_checkpoint_conversion_mapping
from transformers.integrations.sdpa_attention import sdpa_attention_forward
from transformers.models.qwen2_moe.modeling_qwen2_moe import apply_rotary_pos_emb
from transformers.monkey_patching import register_patch_mapping
from transformers.utils.generic import TransformersKwargs
class MoeMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.num_experts = config.num_experts
self.hidden_size = config.hidden_size
self.intermediate_size = config.moe_intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x):
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
return down_proj
# Adapted from the original Qwen2MoeExperts
class ModuleListExperts(nn.ModuleList):
def __init__(self, config):
super().__init__()
self.config = config
self.num_experts = config.num_experts
for _ in range(self.num_experts):
self.append(MoeMLP(config))
def forward(
self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor
) -> torch.Tensor:
final_hidden_states = torch.zeros_like(hidden_states)
with torch.no_grad():
expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
expert_mask = expert_mask.permute(2, 1, 0)
for expert_idx in range(self.num_experts):
top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
current_state = hidden_states[token_idx]
current_hidden_states = self[expert_idx](current_state)
current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
return final_hidden_states
# Adapted from the original Qwen2MoeAttention
class FusedQKVAttention(nn.Module):
def __init__(self, config, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
self.is_causal = True
self.qkv_proj = nn.Linear(config.hidden_size, 3 * config.num_attention_heads * self.head_dim, bias=True)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
if self.config.layer_types[layer_idx] == "sliding_attention":
self.sliding_window = config.sliding_window
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
attention_mask: torch.Tensor | None = None,
past_key_values: Cache | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states, key_states, value_states = self.qkv_proj(hidden_states).chunk(3, dim=-1)
query_states = query_states.view(hidden_shape).transpose(1, 2)
key_states = key_states.view(hidden_shape).transpose(1, 2)
value_states = value_states.view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None:
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
attn_output, attn_weights = sdpa_attention_forward(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
# Registering monkey patches for the new attention and experts modules.
register_patch_mapping(
mapping={
"Qwen2MoeExperts": ModuleListExperts,
"Qwen2MoeAttention": FusedQKVAttention,
}
)
# Registering weight conversion mappings adapted for the new modules. This registration will:
# - Override the original conversion mapping for qwen2_moe which concatenated the experts into a single parameter format.
# - Concatenate the q_proj, k_proj, v_proj weights/biases into a single qkv_proj weight/bias for the new fused attention module.
register_checkpoint_conversion_mapping(
model_type_or_class_name="qwen2_moe",
mapping=[
WeightConverter(
source_patterns=["q_proj", "k_proj", "v_proj"],
target_patterns=["qkv_proj"],
operations=[Concatenate(dim=0)],
),
],
overwrite=True,
)
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B")Ghi lại và phát lại định tuyến chuyên gia MoE
Các quy trình huấn luyện Mixture-of-Experts như RLHF cần ghi lại các chuyên gia mà mỗi token được định tuyến đến trong quá trình sinh, sau đó phát lại chính xác định tuyến đó trong một bước truyền thẳng huấn luyện riêng biệt. Bạn có thể xây dựng điều này từ đầu đến cuối bằng cơ chế monkey patching và bắt đầu output hiện có — không cần thay đổi tệp modeling.
Mẫu này có ba phần:
- Một lớp con của router có thể phát lại có thể tùy chọn đọc các chỉ số chuyên gia được ép buộc từ một thuộc tính của instance.
- Một context manager thiết lập các thuộc tính đó trên mọi router trước một bước forward và xóa chúng sau đó.
- Một mục trong registry bắt đầu ra của mô hình để
output_<name>=Truehiển thị các chỉ số thông qua đường dẫn chuẩn@capture_outputs.
from contextlib import contextmanager
import torch
import torch.nn.functional as F
from transformers import Qwen3MoeConfig, Qwen3MoeForCausalLM
from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeTopKRouter
from transformers.monkey_patching import apply_patches, register_patch_mapping
from transformers.utils.output_capturing import _CAN_RECORD_REGISTRY, OutputRecorder
class ReplayableQwen3MoeTopKRouter(Qwen3MoeTopKRouter):
_forced_indices: torch.Tensor | None = None
def forward(self, hidden_states):
hidden_states = hidden_states.reshape(-1, self.hidden_dim)
router_logits = F.linear(hidden_states, self.weight)
router_logits = F.softmax(router_logits, dtype=torch.float, dim=-1)
if self._forced_indices is not None:
router_indices = self._forced_indices.to(router_logits.device).long()
# Megatron-style replay: preserve expert path, recompute current scores
router_top_value = router_logits.gather(-1, router_indices)
else:
router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1)
if self.norm_topk_prob:
router_top_value = router_top_value / router_top_value.sum(dim=-1, keepdim=True)
return router_logits, router_top_value.to(router_logits.dtype), router_indices
@contextmanager
def replay_moe_routing(model, selected_experts_per_layer):
routers = [m for m in model.modules() if isinstance(m, ReplayableQwen3MoeTopKRouter)]
if len(routers) != len(selected_experts_per_layer):
raise ValueError(f"Got {len(routers)} routers but {len(selected_experts_per_layer)} tensors")
for r, t in zip(routers, selected_experts_per_layer):
r._forced_indices = t
try:
yield
finally:
for r in routers:
r._forced_indices = None
# Swap the router class and construct the model
register_patch_mapping({"Qwen3MoeTopKRouter": ReplayableQwen3MoeTopKRouter})
with apply_patches():
model = Qwen3MoeForCausalLM(Qwen3MoeConfig(...)).eval()
# Expose `output_selected_experts=True` on the base model by adding an OutputRecorder
# at runtime. Index 2 of the router's tuple output is the expert indices.
inner = model.model
existing = _CAN_RECORD_REGISTRY.get(str(inner.__class__), {}) or {}
_CAN_RECORD_REGISTRY[str(inner.__class__)] = {
**existing,
"selected_experts": OutputRecorder(ReplayableQwen3MoeTopKRouter, index=2),
}
# Record
captured = inner(input_ids=input_ids, output_selected_experts=True)
selected_experts = captured.selected_experts # tuple of (num_tokens, top_k) LongTensors
# Replay — same expert path regardless of current router weights
with replay_moe_routing(inner, list(selected_experts)):
outputs = inner(input_ids=input_ids)Replay giữ nguyên các chỉ số chuyên gia chính xác và tính lại điểm định tuyến bằng trọng số router hiện tại, nhờ đó gradient chảy qua các tham số đang hoạt động trong khi việc lựa chọn chuyên gia vẫn được giữ cố định. Đây là hợp đồng replay tối thiểu được sử dụng trong huấn luyện MoE theo phong cách Megatron.
Tương tác với vLLM
Tham số enable_return_routed_experts=True của vLLM sẽ điền dữ liệu vào CompletionOutput.routed_experts dưới dạng mảng np.int32 có kích thước (seq_len, num_layers, top_k). Hãy chuyển đổi nó thành danh sách theo từng lớp mà mẫu này yêu cầu bằng một biểu thức duy nhất:
selected = [
torch.from_numpy(routed_experts[:, layer, :].copy()).long()
for layer in range(routed_experts.shape[1])
]
with replay_moe_routing(model, selected):
loss = model(input_ids=input_ids, labels=labels).lossCông thức tương tự áp dụng cho các họ MoE khác — kế thừa lớp *TopKRouter của họ đó, khớp với hợp đồng trả về gốc (thường là (router_logits, router_scores, router_indices)), và đăng ký bản vá. Xem lớp router của từng mô hình để biết chữ ký chính xác.
Tham khảo API
transformers.monkey_patching.register_patch_mapping
< source >( mapping: dictoverwrite: bool = False )
Tham số
- mapping (
Dict[str, type[nn.Module]]) — Bản ánh xạ từ tên lớp gốc (hoặc mẫu regex) sang các lớp thay thế. Hỗ trợ:- Tên lớp chính xác:
"Qwen2MoeExperts"→CustomExperts - Các mẫu Regex:
".*Attention"khớp vớiLlamaAttention,MistralAttention, v.v., hoặc"^Llama\d+Attention$"khớp vớiLlama2Attention,Llama3Attention, v.v.
Các khớp chính xác có ưu tiên cao hơn các mẫu. Các mẫu được khớp bằng
re.search(), do đó chúng có thể khớp ở bất kỳ đâu trong tên lớp trừ khi bạn sử dụng neo (^cho đầu,$cho cuối). - Tên lớp chính xác:
- overwrite (
bool, tùy chọn, mặc định làFalse) — Có ghi đè lên các ánh xạ hiện có cho các tên lớp đã được đăng ký hay không.
Đăng ký ánh xạ patch để kích hoạt việc vá tự động trong quá trình tạo mô hình bằng from_pretrained, from_config hoặc trong trình quản lý ngữ cảnh apply_patches.
Sử dụng điều này để đăng ký các thay thế lớp sẽ được áp dụng tự động khi tải bất kỳ mô hình nào. Điều này hữu ích cho tính tương thích với thư viện lượng tử hóa, tối ưu hóa cấu trúc và thử nghiệm kiến trúc. Bản ánh xạ là toàn cục, có thể mở rộng qua nhiều lần gọi và có thể được xóa hoàn toàn.
Ví dụ:
from transformers import AutoModelForCausalLM
from transformers.monkey_patching import register_patch_mapping
# Define custom expert implementation
class SequentialExperts(nn.Module):
...
# Register exact class name
register_patch_mapping(
mapping={"Qwen2MoeExperts": SequentialExperts}
)
# Register with regex pattern to match multiple classes
register_patch_mapping(
mapping={".*Attention": CustomAttention} # Matches LlamaAttention, MistralAttention, etc.
)
# Match specific model versions
register_patch_mapping(
mapping={"^Llama\d+Attention$": CustomLlamaAttention} # Matches Llama2Attention, Llama3Attention
)
# The patch will be automatically applied during loading
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")Lưu ý:
Đối với việc chuyển đổi trọng số, hãy sử dụng ~transformers.register_checkpoint_conversion_mapping thay thế.
transformers.monkey_patching.unregister_patch_mapping
< source >( keys: list )
Hủy đăng ký ánh xạ patch để vô hiệu hóa việc vá tự động.
Thao tác này sẽ xóa các ánh xạ được chỉ định khỏi bộ đăng ký toàn cục, ngăn chúng được áp dụng trong quá trình tải mô hình. Bạn phải cung cấp chính xác tên hoặc mẫu đã được sử dụng trong quá trình đăng ký.
Ví dụ:
from transformers import AutoModelForCausalLM
from transformers.monkey_patching import register_patch_mapping, unregister_patch_mapping
# Register a patch
register_patch_mapping(
mapping={"Qwen2MoeExperts": CustomExperts}
)
# Unregister the patch
unregister_patch_mapping(["Qwen2MoeExperts"])
# The patch will no longer be applied during loading
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B")Xóa tất cả các ánh xạ vá đã đăng ký.
Điều này xóa tất cả các ánh xạ đã đăng ký khỏi bộ đăng ký toàn cục.
transformers.monkey_patching.get_patch_mapping
< source >( ) → Dict[str, type[nn.Module]]
Trả về
Dict[str, type[nn.Module]]
Từ điển ánh xạ tên lớp hoặc các mẫu sang các lớp thay thế.
Lấy tất cả các ánh xạ patch đã đăng ký.
Trình quản lý ngữ cảnh để áp dụng các bản vá khỉ (monkey patches) đã đăng ký trong một khối mã.
Điều này tạm thời thay thế các lớp gốc bằng các lớp thay thế đã được đăng ký trong suốt quá trình thực thi khối, và khôi phục các lớp gốc sau đó.
Ví dụ:
from transformers import Qwen2MoeModel, Qwen2MoeConfig
from transformers.monkey_patching import register_patch_mapping, apply_patches
# Register a patch
register_patch_mapping(
mapping={"Qwen2MoeExperts": CustomExperts}
)
# Apply patches within the context
with apply_patches():
# The model will use CustomExperts instead of Qwen2MoeExperts
model = Qwen2MoeModel(Qwen2MoeConfig())
# Outside the context, original classes are restored
# The model will use Qwen2MoeExperts again
model = Qwen2MoeModel(Qwen2MoeConfig())