YUNTA88 commited on
Commit
43b6063
·
verified ·
1 Parent(s): d66d2cd

Upload folder using huggingface_hub

Browse files
patches/.backup_20260224_045354/tokenizer.py.bak ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import warnings
3
+ from pathlib import Path
4
+ from types import MethodType
5
+ from typing import Optional, Union
6
+
7
+ import huggingface_hub
8
+ from transformers import (AutoTokenizer, PreTrainedTokenizer,
9
+ PreTrainedTokenizerFast)
10
+
11
+ from vllm.envs import VLLM_USE_MODELSCOPE
12
+ from vllm.logger import init_logger
13
+ from vllm.lora.request import LoRARequest
14
+ from vllm.transformers_utils.tokenizers import MistralTokenizer
15
+ from vllm.transformers_utils.utils import check_gguf_file
16
+ from vllm.utils import make_async
17
+
18
+ logger = init_logger(__name__)
19
+
20
+ AnyTokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast,
21
+ MistralTokenizer]
22
+
23
+
24
+ def get_cached_tokenizer(tokenizer: AnyTokenizer) -> AnyTokenizer:
25
+ """Get tokenizer with cached properties.
26
+
27
+ This will patch the tokenizer object in place.
28
+
29
+ By default, transformers will recompute multiple tokenizer properties
30
+ each time they are called, leading to a significant slowdown. This
31
+ function caches these properties for faster access."""
32
+
33
+ tokenizer_all_special_ids = set(tokenizer.all_special_ids)
34
+ tokenizer_all_special_tokens_extended = (
35
+ tokenizer.all_special_tokens_extended)
36
+ tokenizer_all_special_tokens = set(tokenizer.all_special_tokens)
37
+ tokenizer_len = len(tokenizer)
38
+
39
+ class CachedTokenizer(tokenizer.__class__): # type: ignore
40
+
41
+ @property
42
+ def all_special_ids(self):
43
+ return tokenizer_all_special_ids
44
+
45
+ @property
46
+ def all_special_tokens(self):
47
+ return tokenizer_all_special_tokens
48
+
49
+ @property
50
+ def all_special_tokens_extended(self):
51
+ return tokenizer_all_special_tokens_extended
52
+
53
+ def __len__(self):
54
+ return tokenizer_len
55
+
56
+ CachedTokenizer.__name__ = f"Cached{tokenizer.__class__.__name__}"
57
+
58
+ tokenizer.__class__ = CachedTokenizer
59
+ return tokenizer
60
+
61
+
62
+ def patch_padding_side(tokenizer: PreTrainedTokenizer) -> None:
63
+ """Patch _pad method to accept `padding_side` for older tokenizers."""
64
+ orig_pad = tokenizer._pad
65
+
66
+ def _pad(
67
+ self: PreTrainedTokenizer,
68
+ *args,
69
+ padding_side: Optional[str] = None,
70
+ **kwargs,
71
+ ):
72
+ if padding_side is not None and padding_side != self.padding_side:
73
+ msg = ("`padding_side` argument is not supported by "
74
+ f"{type(tokenizer).__name__} and will be ignored.")
75
+ warnings.warn(msg, stacklevel=2)
76
+
77
+ return orig_pad(*args, **kwargs)
78
+
79
+ tokenizer._pad = MethodType(_pad, tokenizer)
80
+
81
+
82
+ def get_tokenizer(
83
+ tokenizer_name: Union[str, Path],
84
+ *args,
85
+ tokenizer_mode: str = "auto",
86
+ trust_remote_code: bool = False,
87
+ revision: Optional[str] = None,
88
+ download_dir: Optional[str] = None,
89
+ **kwargs,
90
+ ) -> AnyTokenizer:
91
+ """Gets a tokenizer for the given model name via HuggingFace or ModelScope.
92
+ """
93
+ if VLLM_USE_MODELSCOPE:
94
+ # download model from ModelScope hub,
95
+ # lazy import so that modelscope is not required for normal use.
96
+ # pylint: disable=C.
97
+ from modelscope.hub.snapshot_download import snapshot_download
98
+
99
+ # Only set the tokenizer here, model will be downloaded on the workers.
100
+ if not os.path.exists(tokenizer_name):
101
+ tokenizer_path = snapshot_download(
102
+ model_id=tokenizer_name,
103
+ cache_dir=download_dir,
104
+ revision=revision,
105
+ local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
106
+ # Ignore weights - we only need the tokenizer.
107
+ ignore_file_pattern=[".*.pt", ".*.safetensors", ".*.bin"])
108
+ tokenizer_name = tokenizer_path
109
+
110
+ if tokenizer_mode == "slow":
111
+ if kwargs.get("use_fast", False):
112
+ raise ValueError(
113
+ "Cannot use the fast tokenizer in slow tokenizer mode.")
114
+ kwargs["use_fast"] = False
115
+
116
+ if "truncation_side" not in kwargs:
117
+ kwargs["truncation_side"] = "left"
118
+
119
+ # Separate model folder from file path for GGUF models
120
+ is_gguf = check_gguf_file(tokenizer_name)
121
+ if is_gguf:
122
+ kwargs["gguf_file"] = Path(tokenizer_name).name
123
+ tokenizer_name = Path(tokenizer_name).parent
124
+
125
+ # if tokenizer is from official mistral org
126
+ is_from_mistral_org = str(tokenizer_name).split("/")[0] == "mistralai"
127
+ if is_from_mistral_org and tokenizer_mode != "mistral":
128
+ warnings.warn(
129
+ 'It is strongly recommended to run mistral models with '
130
+ '`--tokenizer_mode "mistral"` to ensure correct '
131
+ 'encoding and decoding.',
132
+ FutureWarning,
133
+ stacklevel=2)
134
+ if tokenizer_mode == "mistral":
135
+ tokenizer = MistralTokenizer.from_pretrained(str(tokenizer_name),
136
+ revision=revision)
137
+ else:
138
+ try:
139
+ tokenizer = AutoTokenizer.from_pretrained(
140
+ tokenizer_name,
141
+ *args,
142
+ trust_remote_code=trust_remote_code,
143
+ revision=revision,
144
+ **kwargs,
145
+ )
146
+ except ValueError as e:
147
+ # If the error pertains to the tokenizer class not existing or not
148
+ # currently being imported,
149
+ # suggest using the --trust-remote-code flag.
150
+ if not trust_remote_code and (
151
+ "does not exist or is not currently imported." in str(e)
152
+ or "requires you to execute the tokenizer file" in str(e)):
153
+ err_msg = ("Failed to load the tokenizer. If the tokenizer "
154
+ "is a custom tokenizer not yet available in the "
155
+ "HuggingFace transformers library, consider "
156
+ "setting `trust_remote_code=True` in LLM or using "
157
+ "the `--trust-remote-code` flag in the CLI.")
158
+ raise RuntimeError(err_msg) from e
159
+ else:
160
+ raise e
161
+
162
+ # NOTE: We can remove this after https://github.com/THUDM/ChatGLM3/issues/1324
163
+ if type(tokenizer).__name__ in ("ChatGLMTokenizer",
164
+ "ChatGLM4Tokenizer"):
165
+ assert isinstance(tokenizer, PreTrainedTokenizer)
166
+ patch_padding_side(tokenizer)
167
+
168
+ if not isinstance(tokenizer, PreTrainedTokenizerFast):
169
+ logger.warning(
170
+ "Using a slow tokenizer. This might cause a significant "
171
+ "slowdown. Consider using a fast tokenizer instead.")
172
+ tokenizer = get_cached_tokenizer(tokenizer)
173
+
174
+ return tokenizer
175
+
176
+
177
+ def get_lora_tokenizer(lora_request: LoRARequest, *args,
178
+ **kwargs) -> Optional[AnyTokenizer]:
179
+ if lora_request is None:
180
+ return None
181
+ try:
182
+ tokenizer = get_tokenizer(lora_request.lora_path, *args, **kwargs)
183
+ except Exception as e:
184
+ # No tokenizer was found in the LoRA folder,
185
+ # use base model tokenizer
186
+ logger.warning(
187
+ "No tokenizer found in %s, using base model tokenizer instead. "
188
+ "(Exception: %s)", lora_request.lora_path, e)
189
+ tokenizer = None
190
+ return tokenizer
191
+
192
+
193
+ get_lora_tokenizer_async = make_async(get_lora_tokenizer)
patches/05_model_config.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Patch Qwen2-VL model config.json for vLLM compatibility.
4
+
5
+ Applies 3 fixes:
6
+ 1. Rename rope_scaling.type -> rope_scaling.rope_type (avoids conflict)
7
+ 2. Add pad_token_id if missing (required by Qwen2Model in vLLM)
8
+ 3. Add text_config block if missing (required by vLLM 0.7.3 for vocab_size etc.)
9
+
10
+ Usage:
11
+ python 05_model_config.py /path/to/model/config.json
12
+
13
+ # Or auto-detect from HuggingFace cache:
14
+ python 05_model_config.py --auto Qwen/Qwen2-VL-2B-Instruct
15
+ """
16
+
17
+ import json
18
+ import sys
19
+ import os
20
+ import shutil
21
+ from pathlib import Path
22
+
23
+
24
+ def find_hf_config(model_name: str) -> str:
25
+ """Find config.json from HuggingFace hub cache."""
26
+ cache_dir = Path.home() / ".cache" / "huggingface" / "hub"
27
+ model_dir = cache_dir / f"models--{model_name.replace('/', '--')}"
28
+
29
+ if not model_dir.exists():
30
+ raise FileNotFoundError(
31
+ f"Model not found in HF cache: {model_dir}\n"
32
+ f"Please download the model first or provide the config.json path directly."
33
+ )
34
+
35
+ # Find the latest snapshot
36
+ snapshots_dir = model_dir / "snapshots"
37
+ if not snapshots_dir.exists():
38
+ raise FileNotFoundError(f"No snapshots found in {model_dir}")
39
+
40
+ snapshots = sorted(snapshots_dir.iterdir(), key=lambda p: p.stat().st_mtime, reverse=True)
41
+ if not snapshots:
42
+ raise FileNotFoundError(f"No snapshots found in {snapshots_dir}")
43
+
44
+ config_path = snapshots[0] / "config.json"
45
+ if not config_path.exists():
46
+ raise FileNotFoundError(f"config.json not found in {snapshots[0]}")
47
+
48
+ return str(config_path)
49
+
50
+
51
+ def patch_config(config_path: str) -> None:
52
+ """Apply all patches to the config.json file."""
53
+ # Backup
54
+ backup_path = config_path + ".bak"
55
+ if not os.path.exists(backup_path):
56
+ shutil.copy2(config_path, backup_path)
57
+ print(f"📁 Backup saved: {backup_path}")
58
+
59
+ with open(config_path, 'r') as f:
60
+ config = json.load(f)
61
+
62
+ changes = []
63
+
64
+ # Fix 1: RoPE scaling type -> rope_type
65
+ if 'rope_scaling' in config:
66
+ rope = config['rope_scaling']
67
+ if 'type' in rope and 'rope_type' not in rope:
68
+ rope['rope_type'] = rope.pop('type')
69
+ changes.append(f"✅ Renamed rope_scaling.type -> rope_type (value: {rope['rope_type']})")
70
+
71
+ # Fix 2: Add pad_token_id
72
+ if 'pad_token_id' not in config:
73
+ pad_id = config.get('bos_token_id', config.get('eos_token_id', 151643))
74
+ config['pad_token_id'] = pad_id
75
+ changes.append(f"✅ Added pad_token_id={pad_id}")
76
+
77
+ # Fix 3: Add text_config block (for vLLM 0.7.3 compatibility)
78
+ if 'text_config' not in config:
79
+ # Build text_config from top-level fields
80
+ text_fields = [
81
+ 'vocab_size', 'hidden_size', 'num_hidden_layers', 'num_attention_heads',
82
+ 'num_key_value_heads', 'intermediate_size', 'hidden_act', 'max_position_embeddings',
83
+ 'rms_norm_eps', 'tie_word_embeddings', 'rope_theta', 'use_sliding_window',
84
+ 'sliding_window', 'max_window_layers', 'attention_dropout',
85
+ ]
86
+ text_config = {}
87
+ for field in text_fields:
88
+ if field in config:
89
+ text_config[field] = config[field]
90
+
91
+ # Always ensure pad_token_id is in text_config
92
+ text_config['pad_token_id'] = config.get('pad_token_id', 151643)
93
+
94
+ if text_config:
95
+ config['text_config'] = text_config
96
+ changes.append(f"✅ Added text_config block ({len(text_config)} fields)")
97
+
98
+ if changes:
99
+ with open(config_path, 'w') as f:
100
+ json.dump(config, f, indent=2, ensure_ascii=False)
101
+ f.write('\n') # trailing newline
102
+ print(f"\n📝 Patched: {config_path}")
103
+ for c in changes:
104
+ print(f" {c}")
105
+ else:
106
+ print(f"\n✅ No changes needed for: {config_path}")
107
+
108
+
109
+ def main():
110
+ if len(sys.argv) < 2:
111
+ print(__doc__)
112
+ sys.exit(1)
113
+
114
+ if sys.argv[1] == '--auto':
115
+ if len(sys.argv) < 3:
116
+ print("Usage: python 05_model_config.py --auto Qwen/Qwen2-VL-2B-Instruct")
117
+ sys.exit(1)
118
+ config_path = find_hf_config(sys.argv[2])
119
+ print(f"🔍 Found config: {config_path}")
120
+ else:
121
+ config_path = sys.argv[1]
122
+
123
+ if not os.path.exists(config_path):
124
+ print(f"❌ File not found: {config_path}")
125
+ sys.exit(1)
126
+
127
+ patch_config(config_path)
128
+
129
+
130
+ if __name__ == '__main__':
131
+ main()
patches/README.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RL4Phyx vLLM Patches
2
+
3
+ 本目录包含 vLLM 0.7.3 的兼容性补丁,用于支持 Qwen2-VL 模型的 RLVR 训练。
4
+
5
+ ## 补丁列表
6
+
7
+ | 文件 | 修改的 vLLM 文件 | 用途 |
8
+ |:---|:---|:---|
9
+ | `01_tokenizer.patch` | `vllm/transformers_utils/tokenizer.py` | `all_special_tokens_extended` 属性降级 |
10
+ | `02_qwen2_getattr.patch` | `vllm/model_executor/models/qwen2.py` | `pad_token_id` / `vocab_size` 安全访问 |
11
+ | `03_qwen2vl_pixels.patch` | `vllm/model_executor/models/qwen2_vl.py` | `min_pixels` / `max_pixels` 默认值 |
12
+ | `04_disabled_tqdm.patch` | `vllm/model_executor/model_loader/weight_utils.py` | 修复 `DisabledTqdm` 重复参数错误 |
13
+ | `05_model_config.py` | 模型 `config.json` | 修复 RoPE + pad_token_id + text_config |
14
+
15
+ ## 使用方法
16
+
17
+ ```bash
18
+ # 激活环境
19
+ conda activate rlvr_vllm # 或 rlvr_train
20
+
21
+ # 一键打补丁
22
+ bash apply_patches.sh
23
+
24
+ # 修复模型 config.json(如需要)
25
+ python 05_model_config.py /path/to/model/config.json
26
+ ```
27
+
28
+ ## 注意事项
29
+
30
+ - 这些补丁适用于 **vLLM 0.7.3**。如使用 0.6.3 版本,部分补丁可能不适用。
31
+ - veRL 框架内部的补丁(`fsdp_workers.py`, `vllm_rollout.py`, `dtensor_weight_loaders.py`)已经集成在项目代码中,无需额外处理。
32
+ - 每次重新安装 vLLM 后需要重新打补丁。
patches/apply_patches.sh ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # ============================================================================
3
+ # RL4Phyx vLLM Patch Applicator
4
+ #
5
+ # Applies all required patches to the vLLM library in the current conda env
6
+ # for Qwen2-VL compatibility.
7
+ #
8
+ # Usage:
9
+ # conda activate rlvr_vllm
10
+ # bash apply_patches.sh
11
+ # ============================================================================
12
+
13
+ set -e
14
+
15
+ # Detect vLLM installation path
16
+ VLLM_PATH=$(python -c "import vllm; import os; print(os.path.dirname(vllm.__file__))" 2>/dev/null)
17
+ if [ -z "$VLLM_PATH" ]; then
18
+ echo "❌ Error: vLLM is not installed in the current environment."
19
+ echo " Please activate the correct conda environment first."
20
+ exit 1
21
+ fi
22
+
23
+ VLLM_VERSION=$(python -c "import vllm; print(vllm.__version__)" 2>/dev/null)
24
+ echo "📦 Detected vLLM $VLLM_VERSION at: $VLLM_PATH"
25
+ echo ""
26
+
27
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
28
+ BACKUP_DIR="$SCRIPT_DIR/.backup_$(date +%Y%m%d_%H%M%S)"
29
+ mkdir -p "$BACKUP_DIR"
30
+
31
+ patch_count=0
32
+ skip_count=0
33
+
34
+ # ============================================================================
35
+ # Patch 1: Tokenizer - all_special_tokens_extended fallback
36
+ # ============================================================================
37
+ TOKENIZER_FILE="$VLLM_PATH/transformers_utils/tokenizer.py"
38
+ echo "🔧 [1/4] Patching tokenizer.py ..."
39
+
40
+ if [ -f "$TOKENIZER_FILE" ]; then
41
+ cp "$TOKENIZER_FILE" "$BACKUP_DIR/tokenizer.py.bak"
42
+
43
+ if grep -q "try:" "$TOKENIZER_FILE" && grep -q "all_special_tokens_extended" "$TOKENIZER_FILE" | grep -q "except"; then
44
+ echo " ⏭️ Already patched, skipping."
45
+ ((skip_count++))
46
+ else
47
+ python3 << 'PYEOF'
48
+ import re
49
+
50
+ file_path = """$TOKENIZER_FILE"""
51
+ with open(file_path, 'r') as f:
52
+ content = f.read()
53
+
54
+ # Replace the direct attribute access with try/except
55
+ old_code = """ tokenizer_all_special_tokens_extended = (
56
+ tokenizer.all_special_tokens_extended)"""
57
+
58
+ new_code = """ try:
59
+ tokenizer_all_special_tokens_extended = (
60
+ tokenizer.all_special_tokens_extended)
61
+ except AttributeError:
62
+ # Fallback for tokenizers missing this attribute (e.g., Qwen2 VLM)
63
+ tokenizer_all_special_tokens_extended = list(tokenizer.all_special_tokens)"""
64
+
65
+ if old_code in content:
66
+ content = content.replace(old_code, new_code)
67
+ with open(file_path, 'w') as f:
68
+ f.write(content)
69
+ print(" ✅ Applied tokenizer patch.")
70
+ else:
71
+ print(" ⚠️ Could not find target code. File may already be patched or version differs.")
72
+ PYEOF
73
+ ((patch_count++))
74
+ fi
75
+ else
76
+ echo " ⚠️ File not found: $TOKENIZER_FILE"
77
+ fi
78
+
79
+ # ============================================================================
80
+ # Patch 2: Qwen2 Model - getattr for pad_token_id and vocab_size
81
+ # ============================================================================
82
+ QWEN2_FILE="$VLLM_PATH/model_executor/models/qwen2.py"
83
+ echo "🔧 [2/4] Patching qwen2.py ..."
84
+
85
+ if [ -f "$QWEN2_FILE" ]; then
86
+ cp "$QWEN2_FILE" "$BACKUP_DIR/qwen2.py.bak"
87
+
88
+ python3 << 'PYEOF'
89
+ file_path = """$QWEN2_FILE"""
90
+ with open(file_path, 'r') as f:
91
+ content = f.read()
92
+
93
+ changes = 0
94
+
95
+ # Patch pad_token_id
96
+ old_pad = "self.padding_idx = config.pad_token_id"
97
+ new_pad = "self.padding_idx = getattr(config, 'pad_token_id', None)"
98
+ if old_pad in content:
99
+ content = content.replace(old_pad, new_pad)
100
+ changes += 1
101
+
102
+ # Patch vocab_size (only the assignment in __init__, not other references)
103
+ old_vocab = "self.vocab_size = config.vocab_size"
104
+ new_vocab = "self.vocab_size = getattr(config, 'vocab_size', None)"
105
+ if old_vocab in content:
106
+ content = content.replace(old_vocab, new_vocab, 1) # Only first occurrence
107
+ changes += 1
108
+
109
+ if changes > 0:
110
+ with open(file_path, 'w') as f:
111
+ f.write(content)
112
+ print(f" ✅ Applied {changes} patches to qwen2.py.")
113
+ else:
114
+ print(" ⚠️ Could not find target code. File may already be patched or version differs.")
115
+ PYEOF
116
+ ((patch_count++))
117
+ else
118
+ echo " ⚠️ File not found: $QWEN2_FILE"
119
+ fi
120
+
121
+ # ============================================================================
122
+ # Patch 3: Qwen2-VL - min_pixels/max_pixels fallback defaults
123
+ # ============================================================================
124
+ QWEN2VL_FILE="$VLLM_PATH/model_executor/models/qwen2_vl.py"
125
+ echo "🔧 [3/4] Patching qwen2_vl.py ..."
126
+
127
+ if [ -f "$QWEN2VL_FILE" ]; then
128
+ cp "$QWEN2VL_FILE" "$BACKUP_DIR/qwen2_vl.py.bak"
129
+
130
+ python3 << 'PYEOF'
131
+ file_path = """$QWEN2VL_FILE"""
132
+ with open(file_path, 'r') as f:
133
+ content = f.read()
134
+
135
+ # Look for _get_max_image_info function's direct access to min_pixels/max_pixels
136
+ # and add safe fallbacks
137
+ old_code = """ min_pixels=max(image_processor.min_pixels, 28 * 28),
138
+ max_pixels=min(image_processor.max_pixels, 1280 * 28 * 28),"""
139
+
140
+ new_code = """ min_pixels=max(getattr(image_processor, 'min_pixels', None) or 3136, 28 * 28),
141
+ max_pixels=min(getattr(image_processor, 'max_pixels', None) or 12845056, 1280 * 28 * 28),"""
142
+
143
+ if old_code in content:
144
+ content = content.replace(old_code, new_code)
145
+ with open(file_path, 'w') as f:
146
+ f.write(content)
147
+ print(" ✅ Applied qwen2_vl pixel fallback patch.")
148
+ else:
149
+ print(" ⚠️ Could not find target code. File may already be patched or version differs.")
150
+ PYEOF
151
+ ((patch_count++))
152
+ else
153
+ echo " ⚠️ File not found: $QWEN2VL_FILE"
154
+ fi
155
+
156
+ # ============================================================================
157
+ # Patch 4: DisabledTqdm - fix duplicate 'disable' kwarg
158
+ # ============================================================================
159
+ WEIGHT_UTILS_FILE="$VLLM_PATH/model_executor/model_loader/weight_utils.py"
160
+ echo "🔧 [4/4] Patching weight_utils.py ..."
161
+
162
+ if [ -f "$WEIGHT_UTILS_FILE" ]; then
163
+ cp "$WEIGHT_UTILS_FILE" "$BACKUP_DIR/weight_utils.py.bak"
164
+
165
+ python3 << 'PYEOF'
166
+ file_path = """$WEIGHT_UTILS_FILE"""
167
+ with open(file_path, 'r') as f:
168
+ content = f.read()
169
+
170
+ old_code = """class DisabledTqdm(tqdm):
171
+
172
+ def __init__(self, *args, **kwargs):
173
+ super().__init__(*args, **kwargs, disable=True)"""
174
+
175
+ new_code = """class DisabledTqdm(tqdm):
176
+
177
+ def __init__(self, *args, **kwargs):
178
+ # Pop 'disable' to avoid duplicate keyword argument error
179
+ kwargs.pop('disable', None)
180
+ super().__init__(*args, **kwargs, disable=True)"""
181
+
182
+ if old_code in content:
183
+ content = content.replace(old_code, new_code)
184
+ with open(file_path, 'w') as f:
185
+ f.write(content)
186
+ print(" ✅ Applied DisabledTqdm patch.")
187
+ else:
188
+ print(" ⚠️ Could not find target code. File may already be patched or version differs.")
189
+ PYEOF
190
+ ((patch_count++))
191
+ else
192
+ echo " ⚠️ File not found: $WEIGHT_UTILS_FILE"
193
+ fi
194
+
195
+ echo ""
196
+ echo "============================================================"
197
+ echo "📋 Summary: $patch_count patches applied, $skip_count skipped"
198
+ echo "📁 Backups saved to: $BACKUP_DIR"
199
+ echo "============================================================"
200
+ echo ""
201
+ echo "💡 Don't forget to also patch model config.json if needed:"
202
+ echo " python $SCRIPT_DIR/05_model_config.py /path/to/model/config.json"
patches/setup_env.sh ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # ============================================================================
3
+ # RL4Phyx Full Environment Setup Script
4
+ #
5
+ # Sets up the complete training environment on a new cluster.
6
+ # Run this after cloning/rsync'ing the RL4Phyx project.
7
+ #
8
+ # Usage:
9
+ # bash setup_env.sh [ENV_NAME]
10
+ # # ENV_NAME defaults to "rlvr_vllm"
11
+ # ============================================================================
12
+
13
+ set -e
14
+
15
+ ENV_NAME="${1:-rlvr_vllm}"
16
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
17
+ PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
18
+
19
+ echo "============================================================"
20
+ echo "🚀 RL4Phyx Environment Setup"
21
+ echo " Environment: $ENV_NAME"
22
+ echo " Project Dir: $PROJECT_DIR"
23
+ echo "============================================================"
24
+
25
+ # Step 1: Create conda environment
26
+ echo ""
27
+ echo "📦 [1/7] Creating conda environment..."
28
+ conda create -n "$ENV_NAME" python=3.10 -y
29
+ eval "$(conda shell.bash hook)"
30
+ conda activate "$ENV_NAME"
31
+
32
+ # Step 2: Install PyTorch (using cu121 to avoid CUDA ABI hell)
33
+ echo ""
34
+ echo "🔥 [2/7] Installing PyTorch (cu121)..."
35
+ pip install torch==2.4.0 torchvision==0.19.0 torchaudio==2.5.1 \
36
+ --index-url https://download.pytorch.org/whl/cu121
37
+
38
+ # Step 3: Install vLLM
39
+ echo ""
40
+ echo "⚡ [3/7] Installing vLLM..."
41
+ pip install vllm==0.6.3
42
+
43
+ # Step 4: Install Flash Attention (pre-compiled wheel)
44
+ echo ""
45
+ echo "💡 [4/7] Installing Flash Attention..."
46
+ # NOTE: Match the wheel to your torch version (torch2.4)
47
+ # Find wheels at: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.7.4.post1
48
+ pip install https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.4cxx11abiFALSE-cp310-cp310-linux_x86_64.whl \
49
+ || echo "⚠️ Flash-attn wheel download failed. Try manually from GitHub releases."
50
+
51
+ # Step 5: Install remaining dependencies
52
+ echo ""
53
+ echo "📚 [5/7] Installing remaining dependencies..."
54
+ pip install ray==2.40.0
55
+ pip install tensordict==0.5.0
56
+ pip install transformers==4.46.3
57
+ pip install qwen-vl-utils
58
+ pip install hydra-core omegaconf
59
+ pip install codetiming
60
+
61
+ # Step 6: Install veRL in editable mode
62
+ echo ""
63
+ echo "🔧 [6/7] Installing veRL (editable mode)..."
64
+ cd "$PROJECT_DIR/ZeroSearch/One-Shot-RLVR"
65
+ pip install -e .
66
+
67
+ # Step 7: Apply vLLM patches
68
+ echo ""
69
+ echo "🩹 [7/7] Applying vLLM patches..."
70
+ bash "$SCRIPT_DIR/apply_patches.sh"
71
+
72
+ echo ""
73
+ echo "============================================================"
74
+ echo "✅ Setup complete!"
75
+ echo ""
76
+ echo "📋 Verification:"
77
+ python -c "
78
+ import torch
79
+ import vllm
80
+ import flash_attn
81
+ import ray
82
+ import tensordict
83
+
84
+ print(f' torch = {torch.__version__}')
85
+ print(f' vllm = {vllm.__version__}')
86
+ print(f' flash_attn = {flash_attn.__version__}')
87
+ print(f' ray = {ray.__version__}')
88
+ print(f' tensordict = {tensordict.__version__}')
89
+ print(f' CUDA = {torch.cuda.is_available()} ({torch.cuda.device_count()} GPUs)')
90
+ "
91
+ echo ""
92
+ echo "📌 Next steps:"
93
+ echo " 1. Set CUDA_HOME: export CUDA_HOME=/usr/local/cuda-12.x"
94
+ echo " 2. Set attention: export VLLM_ATTENTION_BACKEND=XFORMERS"
95
+ echo " 3. Patch model: python $SCRIPT_DIR/05_model_config.py --auto Qwen/Qwen2-VL-2B-Instruct"
96
+ echo " 4. Update paths in training script: scripts/train_bash/train_physics_vlm.sh"
97
+ echo "============================================================"