рд╕рд╛рдордЧреНрд░реА рдкрд░ рдЬрд╛рдПрдВ

рдХреЗ рд▓рд┐рдП рд╕рдВрджрд░реНрдн ultralytics/data/build.py

рдиреЛрдЯ

рдпрд╣ рдлрд╝рд╛рдЗрд▓ рдпрд╣рд╛рдБ рдЙрдкрд▓рдмреНрдз рд╣реИ https://github.com/ultralytics/ultralytics/рдмреВрдБрдж/рдореБрдЦреНрдп/ultralytics/data/build.py рдХрд╛ рдЙрдкрдпреЛрдЧ рдХрд░реЗрдВред рдпрджрд┐ рдЖрдк рдХреЛрдИ рд╕рдорд╕реНрдпрд╛ рджреЗрдЦрддреЗ рд╣реИрдВ рддреЛ рдХреГрдкрдпрд╛ рдкреБрд▓ рдЕрдиреБрд░реЛрдз рдХрд╛ рдпреЛрдЧрджрд╛рди рдХрд░рдХреЗ рдЗрд╕реЗ рдареАрдХ рдХрд░рдиреЗ рдореЗрдВ рдорджрдж рдХрд░реЗрдВ ЁЯЫая╕Пред ЁЯЩП рдзрдиреНрдпрд╡рд╛рдж !



ultralytics.data.build.InfiniteDataLoader

рдХрд╛ рд░реВрдк: DataLoader

рдбреЗрдЯрд╛рд▓реЛрдбрд░ рдЬреЛ рд╢реНрд░рдорд┐рдХреЛрдВ рдХрд╛ рдкреБрди: рдЙрдкрдпреЛрдЧ рдХрд░рддрд╛ рд╣реИред

рд╡реЗрдирд┐рд▓рд╛ рдбреЗрдЯрд╛рд▓реЛрдбрд░ рдХреЗ рд╕рдорд╛рди рд╕рд┐рдВрдЯреИрдХреНрд╕ рдХрд╛ рдЙрдкрдпреЛрдЧ рдХрд░рддрд╛ рд╣реИред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
class InfiniteDataLoader(dataloader.DataLoader):
    """
    Dataloader that reuses workers.

    Uses same syntax as vanilla DataLoader.
    """

    def __init__(self, *args, **kwargs):
        """Dataloader that infinitely recycles workers, inherits from DataLoader."""
        super().__init__(*args, **kwargs)
        object.__setattr__(self, "batch_sampler", _RepeatSampler(self.batch_sampler))
        self.iterator = super().__iter__()

    def __len__(self):
        """Returns the length of the batch sampler's sampler."""
        return len(self.batch_sampler.sampler)

    def __iter__(self):
        """Creates a sampler that repeats indefinitely."""
        for _ in range(len(self)):
            yield next(self.iterator)

    def reset(self):
        """
        Reset iterator.

        This is useful when we want to modify settings of dataset while training.
        """
        self.iterator = self._get_iterator()

__init__(*args, **kwargs)

рдбреЗрдЯрд╛рд▓реЛрдбрд░ рдЬреЛ рд╢реНрд░рдорд┐рдХреЛрдВ рдХреЛ рдЕрд╕реАрдо рд░реВрдк рд╕реЗ рд░реАрд╕рд╛рдпрдХрд▓ рдХрд░рддрд╛ рд╣реИ, рдбреЗрдЯрд╛рд▓реЛрдбрд░ рд╕реЗ рд╡рд┐рд░рд╛рд╕рдд рдореЗрдВ рдорд┐рд▓рд╛ рд╣реИред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def __init__(self, *args, **kwargs):
    """Dataloader that infinitely recycles workers, inherits from DataLoader."""
    super().__init__(*args, **kwargs)
    object.__setattr__(self, "batch_sampler", _RepeatSampler(self.batch_sampler))
    self.iterator = super().__iter__()

__iter__()

рдПрдХ рдирдореВрдирд╛ рдмрдирд╛рддрд╛ рд╣реИ рдЬреЛ рдЕрдирд┐рд╢реНрдЪрд┐рдд рдХрд╛рд▓ рддрдХ рджреЛрд╣рд░рд╛рддрд╛ рд╣реИред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def __iter__(self):
    """Creates a sampler that repeats indefinitely."""
    for _ in range(len(self)):
        yield next(self.iterator)

__len__()

рдмреИрдЪ рд╕реИрдВрдкрд▓рд░ рдХреЗ рд╕реИрдВрдкрд▓рд░ рдХреА рд▓рдВрдмрд╛рдИ рд▓реМрдЯрд╛рддрд╛ рд╣реИред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def __len__(self):
    """Returns the length of the batch sampler's sampler."""
    return len(self.batch_sampler.sampler)

reset()

рдЗрдЯрд░реЗрдЯрд░ рд░реАрд╕реЗрдЯ рдХрд░реЗрдВред

рдпрд╣ рддрдм рдЙрдкрдпреЛрдЧреА рд╣реЛрддрд╛ рд╣реИ рдЬрдм рд╣рдо рдкреНрд░рд╢рд┐рдХреНрд╖рдг рдХреЗ рджреМрд░рд╛рди рдбреЗрдЯрд╛рд╕реЗрдЯ рдХреА рд╕реЗрдЯрд┐рдВрдЧреНрд╕ рдХреЛ рд╕рдВрд╢реЛрдзрд┐рдд рдХрд░рдирд╛ рдЪрд╛рд╣рддреЗ рд╣реИрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def reset(self):
    """
    Reset iterator.

    This is useful when we want to modify settings of dataset while training.
    """
    self.iterator = self._get_iterator()



ultralytics.data.build._RepeatSampler

рдирдореВрдирд╛ рдЬреЛ рд╣рдореЗрд╢рд╛ рдХреЗ рд▓рд┐рдП рджреЛрд╣рд░рд╛рддрд╛ рд╣реИред

рдкреИрд░рд╛рдореАрдЯрд░:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо рдЪреВрдХ
sampler sampler

рджреЛрд╣рд░рд╛рдиреЗ рдХреЗ рд▓рд┐рдП рдирдореВрдирд╛ред

рдЖрд╡рд╢реНрдпрдХ
рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
class _RepeatSampler:
    """
    Sampler that repeats forever.

    Args:
        sampler (Dataset.sampler): The sampler to repeat.
    """

    def __init__(self, sampler):
        """Initializes an object that repeats a given sampler indefinitely."""
        self.sampler = sampler

    def __iter__(self):
        """Iterates over the 'sampler' and yields its contents."""
        while True:
            yield from iter(self.sampler)

__init__(sampler)

рдПрдХ рдСрдмреНрдЬреЗрдХреНрдЯ рдХреЛ рдЗрдирд┐рд╢рд┐рдпрд▓рд╛рдЗрдЬрд╝ рдХрд░рддрд╛ рд╣реИ рдЬреЛ рдХрд┐рд╕реА рджрд┐рдП рдЧрдП рд╕реИрдВрдкрд▓рд░ рдХреЛ рдЕрдирд┐рд╢реНрдЪрд┐рдд рдХрд╛рд▓ рддрдХ рджреЛрд╣рд░рд╛рддрд╛ рд╣реИред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def __init__(self, sampler):
    """Initializes an object that repeats a given sampler indefinitely."""
    self.sampler = sampler

__iter__()

'рдирдореВрдирд╛' рдкрд░ рдкреБрдирд░рд╛рд╡реГрддреНрдд рдХрд░рддрд╛ рд╣реИ рдФрд░ рдЗрд╕рдХреА рд╕рд╛рдордЧреНрд░реА рдЙрддреНрдкрдиреНрди рдХрд░рддрд╛ рд╣реИред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def __iter__(self):
    """Iterates over the 'sampler' and yields its contents."""
    while True:
        yield from iter(self.sampler)



ultralytics.data.build.seed_worker(worker_id)

рдбреЗрдЯрд╛рд▓реЛрдбрд░ рд╡рд░реНрдХрд░ рд╕реАрдб https:// рд╕реЗрдЯ рдХрд░реЗрдВpytorch.org/docs/stable/notes/randomness.html#dataloader рдХрд╛ рдЙрдкрдпреЛрдЧ рдХрд░реЗрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def seed_worker(worker_id):  # noqa
    """Set dataloader worker seed https://pytorch.org/docs/stable/notes/randomness.html#dataloader."""
    worker_seed = torch.initial_seed() % 2**32
    np.random.seed(worker_seed)
    random.seed(worker_seed)



ultralytics.data.build.build_yolo_dataset(cfg, img_path, batch, data, mode='train', rect=False, stride=32, multi_modal=False)

рдирд┐рд░реНрдорд╛рдг рдХрд░ YOLO рдбреЗрдЯрд╛рд╕реЗрдЯред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def build_yolo_dataset(cfg, img_path, batch, data, mode="train", rect=False, stride=32, multi_modal=False):
    """Build YOLO Dataset."""
    dataset = YOLOMultiModalDataset if multi_modal else YOLODataset
    return dataset(
        img_path=img_path,
        imgsz=cfg.imgsz,
        batch_size=batch,
        augment=mode == "train",  # augmentation
        hyp=cfg,  # TODO: probably add a get_hyps_from_cfg function
        rect=cfg.rect or rect,  # rectangular batches
        cache=cfg.cache or None,
        single_cls=cfg.single_cls or False,
        stride=int(stride),
        pad=0.0 if mode == "train" else 0.5,
        prefix=colorstr(f"{mode}: "),
        task=cfg.task,
        classes=cfg.classes,
        data=data,
        fraction=cfg.fraction if mode == "train" else 1.0,
    )



ultralytics.data.build.build_grounding(cfg, img_path, json_file, batch, mode='train', rect=False, stride=32)

рдирд┐рд░реНрдорд╛рдг рдХрд░ YOLO рдбреЗрдЯрд╛рд╕реЗрдЯред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def build_grounding(cfg, img_path, json_file, batch, mode="train", rect=False, stride=32):
    """Build YOLO Dataset."""
    return GroundingDataset(
        img_path=img_path,
        json_file=json_file,
        imgsz=cfg.imgsz,
        batch_size=batch,
        augment=mode == "train",  # augmentation
        hyp=cfg,  # TODO: probably add a get_hyps_from_cfg function
        rect=cfg.rect or rect,  # rectangular batches
        cache=cfg.cache or None,
        single_cls=cfg.single_cls or False,
        stride=int(stride),
        pad=0.0 if mode == "train" else 0.5,
        prefix=colorstr(f"{mode}: "),
        task=cfg.task,
        classes=cfg.classes,
        fraction=cfg.fraction if mode == "train" else 1.0,
    )



ultralytics.data.build.build_dataloader(dataset, batch, workers, shuffle=True, rank=-1)

рдкреНрд░рд╢рд┐рдХреНрд╖рдг рдпрд╛ рд╕рддреНрдпрд╛рдкрди рд╕реЗрдЯ рдХреЗ рд▓рд┐рдП рдПрдХ InfiniteDataLoader рдпрд╛ DataLoader рд▓реМрдЯрд╛рдПрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def build_dataloader(dataset, batch, workers, shuffle=True, rank=-1):
    """Return an InfiniteDataLoader or DataLoader for training or validation set."""
    batch = min(batch, len(dataset))
    nd = torch.cuda.device_count()  # number of CUDA devices
    nw = min([os.cpu_count() // max(nd, 1), workers])  # number of workers
    sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)
    generator = torch.Generator()
    generator.manual_seed(6148914691236517205 + RANK)
    return InfiniteDataLoader(
        dataset=dataset,
        batch_size=batch,
        shuffle=shuffle and sampler is None,
        num_workers=nw,
        sampler=sampler,
        pin_memory=PIN_MEMORY,
        collate_fn=getattr(dataset, "collate_fn", None),
        worker_init_fn=seed_worker,
        generator=generator,
    )



ultralytics.data.build.check_source(source)

рд╕реНрд░реЛрдд рдкреНрд░рдХрд╛рд░ рдХреА рдЬрд╛рдБрдЪ рдХрд░реЗрдВ рдФрд░ рд╕рдВрдмрдВрдзрд┐рдд рдзреНрд╡рдЬ рдорд╛рди рд▓реМрдЯрд╛рдПрдБред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def check_source(source):
    """Check source type and return corresponding flag values."""
    webcam, screenshot, from_img, in_memory, tensor = False, False, False, False, False
    if isinstance(source, (str, int, Path)):  # int for local usb camera
        source = str(source)
        is_file = Path(source).suffix[1:] in (IMG_FORMATS | VID_FORMATS)
        is_url = source.lower().startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://"))
        webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
        screenshot = source.lower() == "screen"
        if is_url and is_file:
            source = check_file(source)  # download
    elif isinstance(source, LOADERS):
        in_memory = True
    elif isinstance(source, (list, tuple)):
        source = autocast_list(source)  # convert all list elements to PIL or np arrays
        from_img = True
    elif isinstance(source, (Image.Image, np.ndarray)):
        from_img = True
    elif isinstance(source, torch.Tensor):
        tensor = True
    else:
        raise TypeError("Unsupported image type. For supported types see https://docs.ultralytics.com/modes/predict")

    return source, webcam, screenshot, from_img, in_memory, tensor



ultralytics.data.build.load_inference_source(source=None, batch=1, vid_stride=1, buffer=False)

рдСрдмреНрдЬреЗрдХреНрдЯ рдбрд┐рдЯреЗрдХреНрд╢рди рдХреЗ рд▓рд┐рдП рдПрдХ рдЕрдиреБрдорд╛рди рд╕реНрд░реЛрдд рд▓реЛрдб рдХрд░рддрд╛ рд╣реИ рдФрд░ рдЖрд╡рд╢реНрдпрдХ рдкрд░рд┐рд╡рд░реНрддрди рд▓рд╛рдЧреВ рдХрд░рддрд╛ рд╣реИред

рдкреИрд░рд╛рдореАрдЯрд░:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо рдЪреВрдХ
source (str, Path, Tensor, Image, ndarray)

рдЕрдиреБрдорд╛рди рдХреЗ рд▓рд┐рдП рдЗрдирдкреБрдЯ рд╕реНрд░реЛрддред

None
batch int

рдбреЗрдЯрд╛рд▓реЛрдбрд░ рдХреЗ рд▓рд┐рдП рдмреИрдЪ рдЖрдХрд╛рд░ред рдбрд┐рдлрд╝реЙрд▓реНрдЯ 1 рд╣реИред

1
vid_stride int

рд╡реАрдбрд┐рдпреЛ рд╕реНрд░реЛрддреЛрдВ рдХреЗ рд▓рд┐рдП рдлреНрд░реЗрдо рдЕрдВрддрд░рд╛рд▓ред рдбрд┐рдлрд╝реЙрд▓реНрдЯ 1 рд╣реИред

1
buffer bool

рдирд┐рд░реНрдзрд╛рд░рд┐рдд рдХрд┐рдпрд╛ рдЧрдпрд╛ рдХрд┐ рд╕реНрдЯреНрд░реАрдо рдлрд╝реНрд░реЗрдо рдмрдлрд░ рдХрд┐рдП рдЬрд╛рдПрдВрдЧреЗ рдпрд╛ рдирд╣реАрдВред рдбрд┐рдлрд╝реЙрд▓реНрдЯ рдЧрд╝рд▓рдд рд╣реИ.

False

рджреЗрддрд╛:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
dataset Dataset

рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдЗрдирдкреБрдЯ рд╕реНрд░реЛрдд рдХреЗ рд▓рд┐рдП рдПрдХ рдбреЗрдЯрд╛рд╕реЗрдЯ рдСрдмреНрдЬреЗрдХреНрдЯред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/data/build.py
def load_inference_source(source=None, batch=1, vid_stride=1, buffer=False):
    """
    Loads an inference source for object detection and applies necessary transformations.

    Args:
        source (str, Path, Tensor, PIL.Image, np.ndarray): The input source for inference.
        batch (int, optional): Batch size for dataloaders. Default is 1.
        vid_stride (int, optional): The frame interval for video sources. Default is 1.
        buffer (bool, optional): Determined whether stream frames will be buffered. Default is False.

    Returns:
        dataset (Dataset): A dataset object for the specified input source.
    """
    source, stream, screenshot, from_img, in_memory, tensor = check_source(source)
    source_type = source.source_type if in_memory else SourceTypes(stream, screenshot, from_img, tensor)

    # Dataloader
    if tensor:
        dataset = LoadTensor(source)
    elif in_memory:
        dataset = source
    elif stream:
        dataset = LoadStreams(source, vid_stride=vid_stride, buffer=buffer)
    elif screenshot:
        dataset = LoadScreenshots(source)
    elif from_img:
        dataset = LoadPilAndNumpy(source)
    else:
        dataset = LoadImagesAndVideos(source, batch=batch, vid_stride=vid_stride)

    # Attach source types to the dataset
    setattr(dataset, "source_type", source_type)

    return dataset





2023-11-12 рдмрдирд╛рдпрд╛ рдЧрдпрд╛, рдЕрдкрдбреЗрдЯ рдХрд┐рдпрд╛ рдЧрдпрд╛ 2024-05-08
рд▓реЗрдЦрдХ: рдмреБрд░рд╣рд╛рди-рдХреНрдпреВ (1), рд▓рд╛рдлрд┐рдВрдЧ-рдХреНрдпреВ (1), рдЧреНрд▓реЗрди-рдЬреЛрдЪрд░ (3)