GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — opencompass/opencompass/tasks/openicl_infer_concurrent.py at main · open-compass/opencompass Expand file tree/ Copy pathopenicl_infer_concurrent.pyMore file actions 361 lines (310 loc) · 13.9 KB / Copy pathopenicl_infer_concurrent.pyFile metadata and controls361 lines (310 loc) · 13.9 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 import argparse import os import os.path as osp import random import sys import threading import time from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from typing import Any, Dict, List, Optional from mmengine.config import Config, ConfigDict from mmengine.utils import mkdir_or_exist import opencompass.datasets # noqa: F401 from opencompass.openicl.icl_inferencer import (ParallelChatInferencer, ParallelChatMLInferencer, ParallelGenInferencer) from opencompass.registry import (ICL_INFERENCERS, ICL_PROMPT_TEMPLATES, ICL_RETRIEVERS, TASKS) from opencompass.tasks.base import BaseTask from opencompass.utils import (InferStatusManager, build_dataset_from_cfg, build_model_from_cfg, get_infer_output_path, get_logger, model_abbr_from_cfg, task_abbr_from_cfg) @dataclass class _ProgressTracker: name: str total: Optional[int] = None completed: int = 0 _lock: threading.Lock = field(default_factory=threading.Lock) def set_total(self, total: int) -> None: with self._lock: self.total = total def set_completed(self, completed: int) -> None: with self._lock: self.completed = completed def incr(self, count: int = 1) -> None: with self._lock: self.completed += count def remaining(self) -> Optional[int]: with self._lock: if self.total is None: return None return max(self.total - self.completed, 0) @dataclass class _RunningTask: name: str progress: _ProgressTracker future: Any @TASKS.register_module() class OpenICLInferConcurrentTask(BaseTask): """Concurrent OpenICL Inference Task for API models.""" name_prefix = 'OpenICLInferConcurrent' log_subdir = 'logs/infer' output_subdir = 'predictions' def __init__(self, cfg: ConfigDict): super().__init__(cfg) run_cfg = self.model_cfgs[0].get('run_cfg', {}) self.num_gpus = run_cfg.get('num_gpus', 0) self.num_procs = run_cfg.get('num_procs', 1) self.logger = get_logger() self.dump_res_length = cfg.get('dump_res_length', False) self.dump_only_message_path = cfg.get('dump_only_message_path', None) self.poll_interval = cfg.get('poll_interval', 1.0) self.log_interval = cfg.get('log_interval', 30.0) def get_command(self, cfg_path, template): sys.path.append(os.getcwd()) script_path = __file__ backend_keys = ['VLLM', 'Lmdeploy'] use_backend = any( key in str(self.model_cfgs[0].get('type', '')) or key in str(self.model_cfgs[0].get('llm', {}).get('type', '')) for key in backend_keys) python = sys.executable if self.num_gpus > 1 and not use_backend: port = random.randint(12000, 32000) command = ( f'{python} -m torch.distributed.run --master_port={port} ' f'--nproc_per_node {self.num_procs} ' f'{script_path} {cfg_path}') else: command = f'{python} {script_path} {cfg_path}' return template.format(task_cmd=command) def run(self, cur_model=None, cur_model_abbr=None): self.logger.info(f'Task {task_abbr_from_cfg(self.cfg)}') failed_tasks = [] for model_cfg, dataset_cfgs in zip(self.model_cfgs, self.dataset_cfgs): self.model_cfg = model_cfg if cur_model and cur_model_abbr == model_abbr_from_cfg(model_cfg): self.model = cur_model else: self.model = build_model_from_cfg(model_cfg) tasks = [] for dataset_cfg in dataset_cfgs: out_path = get_infer_output_path( model_cfg, dataset_cfg, osp.join(self.work_dir, 'predictions')) if osp.exists(out_path): continue tasks.append(dataset_cfg) if not tasks: continue # Default concurrent controls from run_cfg or model config. max_workers = model_cfg.get('max_workers', self._default_max_workers()) max_workers = max(1, int(max_workers)) tokens = threading.Semaphore(max_workers) self.logger.info( f'Concurrent infer settings: max_workers={max_workers}.') failed_tasks.extend( self._run_task_group(model_cfg, tasks, tokens, max_workers)) if failed_tasks: failed_task_names = ', '.join(failed_tasks) raise RuntimeError( f'Concurrent inference failed for {len(failed_tasks)} ' f'dataset task(s): {failed_task_names}') def _default_max_workers(self) -> int: cpu_count = os.cpu_count() or 1 return min(32, cpu_count + 4) def _inferencer_name(self, inferencer_type) -> str: if isinstance(inferencer_type, str): return inferencer_type.split('.')[-1] return inferencer_type.__name__ def _set_default_value(self, cfg: ConfigDict, key: str, value: Any): if key not in cfg: cfg[key] = value def _build_inferencer(self, model, model_cfg, dataset_cfg, max_workers): infer_cfg = dataset_cfg['infer_cfg'] inferencer_cfg = infer_cfg['inferencer'].copy() inferencer_type = self._inferencer_name(inferencer_cfg.get('type')) if self.dump_only_message_path: # Skip inferencer type modification if dump only message. pass elif inferencer_type == 'GenInferencer': inferencer_cfg['type'] = ParallelGenInferencer elif inferencer_type == 'ChatInferencer': inferencer_cfg['type'] = ParallelChatInferencer elif inferencer_type == 'ChatMLInferencer': inferencer_cfg['type'] = ParallelChatMLInferencer if inferencer_type not in ( 'ChatInferencer', 'GenInferencer', 'ChatMLInferencer', 'ParallelChatInferencer', 'ParallelGenInferencer', 'ParallelChatMLInferencer', ): raise NotImplementedError( f'Unsupported inferencer type `{inferencer_type}` ' 'for OpenICLInferTaskConcurrent') inferencer_cfg.setdefault('max_infer_workers', max_workers) inferencer_cfg['model'] = model self._set_default_value(inferencer_cfg, 'max_out_len', model_cfg.get('max_out_len', None)) self._set_default_value(inferencer_cfg, 'min_out_len', model_cfg.get('min_out_len', None)) inferencer_cfg['max_seq_len'] = model_cfg.get('max_seq_len') inferencer_cfg['dump_res_length'] = self.dump_res_length inferencer_cfg['dump_only_message_path'] = self.dump_only_message_path return ICL_INFERENCERS.build(inferencer_cfg) def _run_dataset_task(self, model_cfg, dataset_cfg, tokens, max_workers, progress: _ProgressTracker, status: InferStatusManager): try: model = self.model if model.is_api: model.tokens = tokens else: raise RuntimeError( 'OpenICLInferTaskConcurrent only supports API models, ' f'got {type(model)} instead.') dataset = build_dataset_from_cfg(dataset_cfg) progress.set_total(len(dataset.test)) infer_cfg = dataset_cfg['infer_cfg'] assert hasattr(infer_cfg, 'ice_template') or hasattr( infer_cfg, 'prompt_template'), ( 'Both ice_template and prompt_template cannot be None ' 'simultaneously.') retriever_cfg = infer_cfg['retriever'].copy() retriever_cfg['dataset'] = dataset retriever = ICL_RETRIEVERS.build(retriever_cfg) inferencer = self._build_inferencer(model, model_cfg, dataset_cfg, max_workers) if hasattr(inferencer, 'progress_tracker'): inferencer.progress_tracker = progress out_path = get_infer_output_path( model_cfg, dataset_cfg, osp.join(self.work_dir, 'predictions')) out_dir, out_file = osp.split(out_path) mkdir_or_exist(out_dir) infer_kwargs = dict( output_json_filepath=out_dir, output_json_filename=out_file, ) if 'prompt_template' in infer_cfg: infer_kwargs['prompt_template'] = ICL_PROMPT_TEMPLATES.build( infer_cfg['prompt_template']) if 'ice_template' in infer_cfg: infer_kwargs['ice_template'] = ICL_PROMPT_TEMPLATES.build( infer_cfg['ice_template']) inferencer.inference(retriever, **infer_kwargs) except Exception as e: import traceback status.update(status='fail') trace = '\n'.join(traceback.format_exception(e)) self.logger.error(f'Infer failed with\n{trace}') else: status.update(status='done') def _remaining_total(self, running: List[_RunningTask], max_pending_samples: int) -> int: total = 0 for item in running: remaining = item.progress.remaining() if remaining is None: return max_pending_samples total += remaining return total def _run_task_group(self, model_cfg, tasks, tokens, max_workers): pending = list(tasks) running: List[_RunningTask] = [] last_log = 0.0 abbr_counts = {} for dataset_cfg in pending: abbr = dataset_cfg.get('abbr', 'task') abbr_counts[abbr] = abbr_counts.get(abbr, 0) + 1 status_entries: Dict[str, InferStatusManager] = {} for dataset_cfg in pending: task_name = task_abbr_from_cfg({ 'models': [model_cfg], 'datasets': [[dataset_cfg]], }) abbr = dataset_cfg.get('abbr', 'task') status_entries[task_name] = InferStatusManager( self.work_dir, model_cfg, dataset_cfg) status_entries[task_name].update(status='pending') max_parallel_ds = min(len(pending), 32) or 1 with ThreadPoolExecutor(max_workers=max_parallel_ds) as executor: while pending or running: # collect finished tasks finished = [] for item in running: if item.future.done(): finished.append(item) self.logger.info(f'Finished dataset task {item.name}') if finished: running = [ item for item in running if item not in finished ] # Start next sub task # Load next dataset with 100% overhead. max_pending_samples = max(1, int(max_workers * 2)) remaining_total = self._remaining_total( running, max_pending_samples) while pending and remaining_total < max_pending_samples: dataset_cfg = pending.pop(0) task_name = task_abbr_from_cfg({ 'models': [model_cfg], 'datasets': [[dataset_cfg]], }) progress = _ProgressTracker(task_name) entry = status_entries.get(task_name) if entry is not None: entry.update(status='running') future = executor.submit( self._run_dataset_task, model_cfg, dataset_cfg, tokens, max_workers, progress, status_entries[task_name], ) running.append(_RunningTask(task_name, progress, future)) self.logger.info(f'Start dataset task {task_name}') remaining_total = self._remaining_total( running, max_pending_samples) now = time.time() if now - last_log >= self.log_interval and running: status = [] for item in running: total = (item.progress.total if item.progress.total is not None else '?') status.append( f'{item.name}:{item.progress.completed}/{total}') self.logger.info(f'Running tasks: {", ".join(status)}') last_log = now for item in finished + running: entry = status_entries.get(item.name) if entry is not None: entry.update( total=item.progress.total, completed=item.progress.completed, ) if running: time.sleep(self.poll_interval) return [ task_name for task_name, entry in status_entries.items() if entry.infer_status.get('status') == 'fail' ] def parse_args(): parser = argparse.ArgumentParser(description='Model Inferencer') parser.add_argument('config', help='Config file path') args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() cfg = Config.fromfile(args.config) start_time = time.time() inferencer = OpenICLInferConcurrentTask(cfg) inferencer.run() end_time = time.time() get_logger().info(f'time elapsed: {end_time - start_time:.2f}s') |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |