torch_world.datasets
INFO
このページはまだ翻訳されていません。 英語版を読む
class TrajectoryDataset
TrajectoryDataset(
episodes: dict[str, Tensor],
window: int,
frameskip: int = 1,
stacked: tuple[str, ...] = ("actions",),
)Sliding windows of window steps over episodes stored as tensors (N, T, ...) with a shared T.
With a frameskip of k, a window keeps every k-th frame and each of its steps concatenates the k environment actions that follow the frame, so actions (N, T, A) become (window, k * A), as DINO-WM and LeWM train. stacked names the keys whose k steps are concatenated; the others are subsampled.
Source code in torch_world/datasets/trajectories.py
class TrajectoryDataset(Dataset):
"""Sliding windows of ``window`` steps over episodes stored as tensors ``(N, T, ...)`` with a shared ``T``.
With a ``frameskip`` of ``k``, a window keeps every ``k``-th frame and each of its steps concatenates the ``k``
environment actions that follow the frame, so ``actions`` ``(N, T, A)`` become ``(window, k * A)``, as DINO-WM and
LeWM train. ``stacked`` names the keys whose ``k`` steps are concatenated; the others are subsampled.
"""
def __init__(
self, episodes: dict[str, Tensor], window: int, frameskip: int = 1, stacked: tuple[str, ...] = ("actions",)
):
self.episodes = episodes
self.window, self.frameskip, self.stacked = window, frameskip, stacked
self.num_episodes, self.length = next(iter(episodes.values())).shape[:2]
self.per_episode = self.length - window * frameskip + 1
def __len__(self) -> int:
return self.num_episodes * self.per_episode
def __getitem__(self, i: int) -> dict[str, Tensor]:
e, t = divmod(i, self.per_episode)
k, end = self.frameskip, t + self.window * self.frameskip
return {
key: v[e, t:end].reshape(self.window, k * v.size(-1)) if key in self.stacked else v[e, t:end:k]
for key, v in self.episodes.items()
}class LatentClips
LatentClips(root: str | Path, pattern: str = "*.pt")Clips precomputed into shards on disk, such as video-autoencoder latents with their actions and goals.
Every *.pt file in root holds {name: (N, ...)} tensors written by write_latent_shard, for example latents, actions and goal. Shards are memory-mapped, so a dataset larger than RAM streams from disk, and each worker of a DataLoader opens only the shards it reads. Item i is {name: tensor[i]}.
Source code in torch_world/datasets/latents.py
class LatentClips(Dataset):
"""Clips precomputed into shards on disk, such as video-autoencoder latents with their actions and goals.
Every ``*.pt`` file in ``root`` holds ``{name: (N, ...)}`` tensors written by ``write_latent_shard``, for
example ``latents``, ``actions`` and ``goal``. Shards are memory-mapped, so a dataset larger than RAM streams from
disk, and each worker of a ``DataLoader`` opens only the shards it reads. Item ``i`` is ``{name: tensor[i]}``.
"""
def __init__(self, root: str | Path, pattern: str = "*.pt"):
self.paths = sorted(Path(root).glob(pattern))
if not self.paths:
raise FileNotFoundError(f"No shards matching {pattern} in {root}")
sizes = []
for path in self.paths:
shard = torch.load(path, mmap=True, weights_only=True)
sizes.append(next(iter(shard.values())).size(0))
self.offsets = [0]
for size in sizes:
self.offsets.append(self.offsets[-1] + size)
self._open: dict[int, dict[str, Tensor]] = {}
def __len__(self) -> int:
return self.offsets[-1]
def _shard(self, s: int) -> dict[str, Tensor]:
if s not in self._open:
self._open[s] = torch.load(self.paths[s], mmap=True, weights_only=True)
return self._open[s]
def __getitem__(self, i: int) -> dict[str, Tensor]:
if not 0 <= i < len(self):
raise IndexError(i)
s = bisect.bisect_right(self.offsets, i) - 1
return {k: v[i - self.offsets[s]] for k, v in self._shard(s).items()}function write_latent_shard
write_latent_shard(path: str | Path, **tensors: Tensor) -> PathSave one shard of clips, {name: (N, ...)} with a shared N, atomically as path.
Source code in torch_world/datasets/latents.py
def write_latent_shard(path: str | Path, **tensors: Tensor) -> Path:
"""Save one shard of clips, ``{name: (N, ...)}`` with a shared ``N``, atomically as ``path``."""
sizes = {v.size(0) for v in tensors.values()}
if len(sizes) != 1:
raise ValueError("Every tensor of a shard needs the same number of clips")
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp")
torch.save({k: v.detach().cpu().contiguous() for k, v in tensors.items()}, tmp)
tmp.replace(path)
return pathfunction load_ogbench
load_ogbench(
name: str,
split: str = "train",
dataset_dir: str | Path = "~/.ogbench/data",
info: bool = False,
) -> dict[str, Tensor]Episodes of an OGBench dataset as tensors (N, T, ...), ready for a TrajectoryDataset.
observations are float32 state vectors, or visual- uint8 images (N, T, 3, H, W) kept in uint8 to save memory: divide by 255 for [0, 1]. actions are (N, T, A); the action after the last frame of an episode has no next frame, as in OGBench. info=True adds qpos, qvel and, where recorded, button_states. Missing files are downloaded with OGBench into dataset_dir.
Source code in torch_world/datasets/ogbench.py
def load_ogbench(
name: str, split: str = "train", dataset_dir: str | Path = "~/.ogbench/data", info: bool = False
) -> dict[str, Tensor]:
"""Episodes of an OGBench dataset as tensors ``(N, T, ...)``, ready for a `TrajectoryDataset`.
``observations`` are float32 state vectors, or ``visual-`` uint8 images ``(N, T, 3, H, W)`` kept in uint8 to
save memory: divide by 255 for [0, 1]. ``actions`` are ``(N, T, A)``; the action after the last frame of an
episode has no next frame, as in OGBench. ``info=True`` adds ``qpos``, ``qvel`` and, where recorded,
``button_states``. Missing files are downloaded with OGBench into ``dataset_dir``.
"""
import numpy as np
if split not in ("train", "val"):
raise ValueError("split must be 'train' or 'val'")
if "-singletask" in name:
raise ValueError("Single-task data is the goal-conditioned dataset relabelled; load it by its base name")
dataset_dir = Path(dataset_dir).expanduser()
path = dataset_dir / f"{name}{'-val' if split == 'val' else ''}.npz"
if not path.is_file():
try:
import ogbench
except ImportError as exc:
raise ImportError("Install OGBench to download its datasets: pip install 'torch-world[ogbench]'") from exc
ogbench.download_datasets([name], str(dataset_dir))
with np.load(path) as file:
# Each episode ends at a terminal step; the file stores episodes back to back.
ends = np.flatnonzero(file["terminals"]) + 1
lengths = np.unique(np.diff(ends, prepend=0))
if len(lengths) != 1 or ends[-1] != len(file["terminals"]):
raise ValueError(f"{name} has episodes of different lengths {lengths.tolist()}; cannot stack them")
keys = ["observations", "actions"] + [k for k in ("qpos", "qvel", "button_states") if info and k in file]
episodes = {k: torch.from_numpy(file[k].reshape(len(ends), int(lengths[0]), *file[k].shape[1:])) for k in keys}
obs = episodes["observations"]
if obs.dtype == torch.uint8:
episodes["observations"] = obs.permute(0, 1, 4, 2, 3)
else:
episodes["observations"] = obs.float()
episodes["actions"] = episodes["actions"].float()
return episodesfunction load_robocasa
load_robocasa(
root: str | Path,
episode: int,
*,
camera: str = "robot0_agentview_left",
size: int = 128,
) -> dict[str, Tensor]One episode of a RoboCasa dataset, a LeRobot directory, as tensors (1, T, ...) for a TrajectoryDataset.
observations are camera frames (1, T, 3, size, size) in uint8. actions (1, T, 12) are reordered from the dataset's layout to the order RoboCasa environments take; states (1, T, 16) are the dataset's observation.state: base position and rotation, end effector pose relative to the base, gripper joints. Episodes differ in length, so combine them with ConcatDataset. Needs the robocasa extra.
Source code in torch_world/datasets/robocasa.py
def load_robocasa(
root: str | Path, episode: int, *, camera: str = "robot0_agentview_left", size: int = 128
) -> dict[str, Tensor]:
"""One episode of a RoboCasa dataset, a LeRobot directory, as tensors ``(1, T, ...)`` for a `TrajectoryDataset`.
``observations`` are ``camera`` frames ``(1, T, 3, size, size)`` in uint8. ``actions`` ``(1, T, 12)`` are reordered
from the dataset's layout to the order `RoboCasa` environments take; ``states`` ``(1, T, 16)`` are the dataset's
``observation.state``: base position and rotation, end effector pose relative to the base, gripper joints.
Episodes differ in length, so combine them with ``ConcatDataset``. Needs the ``robocasa`` extra.
"""
import numpy as np
try:
import av
import pyarrow.parquet as pq
except ImportError as exc:
raise ImportError("Reading RoboCasa datasets needs: pip install 'torch-world[robocasa]'") from exc
root = Path(root)
info = json.loads((root / "meta" / "info.json").read_text())
modality = json.loads((root / "meta" / "modality.json").read_text())
chunk = episode // info["chunks_size"]
table = pq.read_table(root / info["data_path"].format(episode_chunk=chunk, episode_index=episode))
stored = np.stack(table.column("action").to_numpy(zero_copy_only=False)).astype(np.float32)
actions = np.zeros_like(stored)
for key, (start, end) in ACTION_LAYOUT.items():
actions[:, start:end] = stored[:, modality["action"][key]["start"] : modality["action"][key]["end"]]
states = np.stack(table.column("observation.state").to_numpy(zero_copy_only=False)).astype(np.float32)
video = root / info["video_path"].format(
episode_chunk=chunk, video_key=f"observation.images.{camera}", episode_index=episode
)
with av.open(str(video)) as container:
frames = np.stack([frame.to_ndarray(format="rgb24") for frame in container.decode(video=0)])
if len(frames) != len(actions):
raise ValueError(f"episode {episode}: {len(frames)} frames but {len(actions)} actions")
return {
"observations": resize_images(torch.from_numpy(frames), size)[None],
"states": torch.from_numpy(states)[None],
"actions": torch.from_numpy(actions)[None],
}function load_robocasa_scene
load_robocasa_scene(root: str | Path, episode: int) -> dictThe kitchen and initial simulator state of one demonstration, for RoboCasa.reset(scenes=...).
Returns ep_meta (layout, style, objects and the language instruction), model (the scene's MJCF) and state, the flattened MuJoCo state at the first step, as RoboCasa stores them in extras/.
Source code in torch_world/datasets/robocasa.py
def load_robocasa_scene(root: str | Path, episode: int) -> dict:
"""The kitchen and initial simulator state of one demonstration, for ``RoboCasa.reset(scenes=...)``.
Returns ``ep_meta`` (layout, style, objects and the language instruction), ``model`` (the scene's MJCF) and
``state``, the flattened MuJoCo state at the first step, as RoboCasa stores them in ``extras/``.
"""
import gzip
import numpy as np
extras = Path(root) / "extras" / f"episode_{episode:06d}"
with np.load(extras / "states.npz") as states:
state = states["states"][0]
return {
"ep_meta": json.loads((extras / "ep_meta.json").read_text()),
"model": gzip.decompress((extras / "model.xml.gz").read_bytes()).decode(),
"state": state,
}function load_robodojo
load_robodojo(
path: str | Path | BinaryIO,
*,
camera: str = "cam_head",
size: int = 64,
action_type: str = "joint",
robot: dict | None = None,
) -> dict[str, Tensor]One RoboDojo episode, an XPolicyLab v1.0 HDF5 file, as tensors (1, T, ...) for a TrajectoryDataset.
observations are camera frames (1, T, 3, size, size) in uint8, states and actions the packed robot vectors of robot_layout (1, T, D) in robot units: joint angles in radians and grippers in [0, 1]. Episodes differ in length, so combine them with ConcatDataset. path may be an open file, such as HfFileSystem().open(...), which reads only the arrays used rather than every camera. Encoded frames are decoded with XPolicyLab's decode_image_bit, the only decoder that gets both of its byte formats right.
Source code in torch_world/datasets/robodojo.py
def load_robodojo(
path: str | Path | BinaryIO,
*,
camera: str = "cam_head",
size: int = 64,
action_type: str = "joint",
robot: dict | None = None,
) -> dict[str, Tensor]:
"""One RoboDojo episode, an XPolicyLab v1.0 HDF5 file, as tensors ``(1, T, ...)`` for a `TrajectoryDataset`.
``observations`` are ``camera`` frames ``(1, T, 3, size, size)`` in uint8, ``states`` and ``actions`` the packed
robot vectors of `robot_layout` ``(1, T, D)`` in robot units: joint angles in radians and grippers in [0, 1].
Episodes differ in length, so combine them with ``ConcatDataset``. ``path`` may be an open file, such as
``HfFileSystem().open(...)``, which reads only the arrays used rather than every camera. Encoded frames are
decoded with XPolicyLab's ``decode_image_bit``, the only decoder that gets both of its byte formats right.
"""
import numpy as np
try:
import h5py
except ImportError as exc:
raise ImportError("Install h5py to read RoboDojo episodes: pip install 'torch-world[robodojo]'") from exc
with h5py.File(path, "r") as file:
colors = file["vision"][camera]["colors"]
if colors.dtype == np.uint8 and colors.ndim == 4:
frames = resize_images(colors[()], size)
else:
try:
from XPolicyLab.utils.process_data import decode_image_bit
except ImportError as exc:
raise ImportError("Encoded RoboDojo frames need XPolicyLab on the Python path to decode") from exc
frames = torch.cat(
[resize_images(decode_image_bit(colors[i : i + 64]), size) for i in range(0, len(colors), 64)]
)
layout = robot_layout(action_type, robot, plural=True)
states, actions = pack(file["state"], layout), pack(file["action"], layout)
if not len(frames) == len(states) == len(actions):
raise ValueError(f"{path}: {len(frames)} frames, {len(states)} states and {len(actions)} actions differ")
return {
"observations": frames[None],
"states": torch.from_numpy(states)[None],
"actions": torch.from_numpy(actions)[None],
}function robot_layout
robot_layout(
action_type: str = "joint", robot: dict | None = None, plural: bool = False
) -> list[tuple[str, int]]Keys and widths of a packed robot vector [left arm, left gripper, right arm, right gripper].
Runtime observations and actions use singular keys (left_arm_joint_state); trajectory files use plural ones (left_arm_joint_states). action_type="ee" replaces each arm's joints by its 7-value pose [x, y, z, qw, qx, qy, qz].
Source code in torch_world/datasets/robodojo.py
def robot_layout(action_type: str = "joint", robot: dict | None = None, plural: bool = False) -> list[tuple[str, int]]:
"""Keys and widths of a packed robot vector ``[left arm, left gripper, right arm, right gripper]``.
Runtime observations and actions use singular keys (``left_arm_joint_state``); trajectory files use plural ones
(``left_arm_joint_states``). ``action_type="ee"`` replaces each arm's joints by its 7-value pose
``[x, y, z, qw, qx, qy, qz]``.
"""
robot = DUAL_X5 if robot is None else robot
if action_type not in ("joint", "ee"):
raise ValueError("action_type must be 'joint' or 'ee'")
if len(robot["arm_dim"]) != 2 or len(robot["ee_dim"]) != 2:
raise ValueError("RoboDojo's target robots have two arms; pass arm_dim and ee_dim for both")
s = "s" if plural else ""
layout = []
for side, arm_dim, ee_dim in zip(("left", "right"), robot["arm_dim"], robot["ee_dim"]):
arm = (f"{side}_arm_joint_state{s}", arm_dim) if action_type == "joint" else (f"{side}_ee_pose{s}", 7)
layout += [arm, (f"{side}_ee_joint_state{s}", ee_dim)]
return layoutfunction read_video
read_video(
path: str, size: tuple[int, int] | None = None, device=None
) -> TensorEvery frame of a video file as (F, 3, H, W) in [0, 1], resized to size when given. Needs av.
Source code in torch_world/datasets/videos.py
def read_video(path: str, size: tuple[int, int] | None = None, device=None) -> Tensor:
"""Every frame of a video file as ``(F, 3, H, W)`` in ``[0, 1]``, resized to ``size`` when given. Needs ``av``."""
import av
import numpy as np
with av.open(str(path)) as container:
frames = np.stack([frame.to_ndarray(format="rgb24") for frame in container.decode(video=0)])
frames = torch.from_numpy(frames).to(device).permute(0, 3, 1, 2).float().div(255)
return frames if size is None else F.interpolate(frames, size=size, mode="bilinear", antialias=True)function random_clips
random_clips(
frames: Tensor,
n: int,
length: int,
size: int,
stride: int = 1,
generator: torch.Generator | None = None,
) -> Tensorn clips (n, 3, length, size, size) of frames (F, 3, H, W): each a fixed square window, at a random place and time, over length frames stride apart, as a fixed camera films them.
Source code in torch_world/datasets/videos.py
def random_clips(
frames: Tensor, n: int, length: int, size: int, stride: int = 1, generator: torch.Generator | None = None
) -> Tensor:
"""``n`` clips ``(n, 3, length, size, size)`` of ``frames`` ``(F, 3, H, W)``: each a fixed square window, at a
random place and time, over ``length`` frames ``stride`` apart, as a fixed camera films them."""
F_, _, H, W = frames.shape
start = torch.randint(F_ - (length - 1) * stride, (n,), generator=generator)
y, x = (
torch.randint(H - size + 1, (n,), generator=generator),
torch.randint(W - size + 1, (n,), generator=generator),
)
time = start[:, None] + stride * torch.arange(length)
rows, cols = y[:, None] + torch.arange(size), x[:, None] + torch.arange(size)
clips = frames[time[:, :, None, None], :, rows[:, None, :, None], cols[:, None, None, :]] # (n, T, S, S, 3)
return clips.permute(0, 4, 1, 2, 3)class MedMNIST
MedMNIST(
name: str,
split: str = "train",
size: int = 64,
root: str | Path | None = None,
download: bool = True,
)A MedMNIST v2 dataset: images (N, 3, size, size) uint8 and labels (N,).
The .npz file is downloaded once from Zenodo into root and checked against its MD5. Grayscale images are repeated to three channels. Items are {"image", "label"}. The data is licensed CC BY 4.0.
Yang et al., "MedMNIST v2: A large-scale lightweight benchmark for 2D and 3D biomedical image classification", Scientific Data 2023. Paper: https://arxiv.org/abs/2110.14795 Data: https://zenodo.org/records/10519652
Source code in torch_world/datasets/medmnist.py
class MedMNIST(Dataset):
"""A MedMNIST v2 dataset: ``images`` ``(N, 3, size, size)`` uint8 and ``labels`` ``(N,)``.
The ``.npz`` file is downloaded once from Zenodo into ``root`` and checked against its MD5. Grayscale images are
repeated to three channels. Items are ``{"image", "label"}``. The data is licensed CC BY 4.0.
Yang et al., "MedMNIST v2: A large-scale lightweight benchmark for 2D and 3D biomedical image classification",
Scientific Data 2023.
Paper: https://arxiv.org/abs/2110.14795
Data: https://zenodo.org/records/10519652
"""
def __init__(
self, name: str, split: str = "train", size: int = 64, root: str | Path | None = None, download: bool = True
):
self.name, self.split, self.size = name, split, size
self.modality, self.classes, self.malignant = INFO[name]
arrays = _read_npz(self._fetch(Path(root or Path.home() / ".cache" / "torch_world" / "medmnist"), download))
images = arrays[f"{split}_images"]
images = images[..., None].expand(*images.shape, 3) if images.dim() == 3 else images
self.images = images.permute(0, 3, 1, 2).contiguous()
self.labels = arrays[f"{split}_labels"].flatten().long()
def _fetch(self, root: Path, download: bool) -> Path:
file = f"{self.name}.npz" if self.size == 28 else f"{self.name}_{self.size}.npz"
path = root / file
if not path.exists():
if not download:
raise FileNotFoundError(path)
root.mkdir(parents=True, exist_ok=True)
urllib.request.urlretrieve(URL.format(file=file), path)
md5 = hashlib.md5(path.read_bytes()).hexdigest()
if md5 != MD5[self.name][SIZES.index(self.size)]:
raise RuntimeError(f"{path} is corrupt (md5 {md5}); delete it and download again")
return path
def __len__(self) -> int:
return len(self.labels)
def __getitem__(self, i: int) -> dict:
return {"image": self.images[i], "label": self.labels[i]}
@property
def info(self) -> str:
return f"{self.name} ({self.split}): {self.modality}, {len(self.classes)} classes, {len(self)} images"class MedicalVQA
MedicalVQA(
names: list[str],
split: str = "train",
size: int = 64,
root: str | Path | None = None,
download: bool = True,
seed: int = 0,
)Templated visual question answering over MedMNIST datasets, in the style of the MMBU challenge.
Every image yields a modality question; datasets with more than two classes add a finding question and a verification of a named finding (true half of the time, drawn with seed); datasets with malignant classes add a malignancy question. Items are {"image", "caption", "question", "answer", "kind"}.
images holds every image once as uint8. After encode(encoder), items carry the encoder's cached outputs in place of the images, so a frozen encoder runs once per image instead of once per question.
MMBU challenge: https://akiranishii.github.io/mmbu-challenge/
Members
| Member | Description |
|---|---|
info | A table of the source datasets and of the questions of each kind. |
examples | The first per_source images of each source dataset and their findings, for plots.images. |
pixels | The uint8 images of the given items. |
encode | Cache encoder(images), run on device (by default the encoder's); items then carry the outputs. |
texts | Every caption, question and answer the templates can produce for these datasets. |
answers | The candidate answers for retrieval: every answer the templates can produce. |
weights | Per-item sampling weights that give each source dataset the same total weight. |
Source code in torch_world/datasets/medmnist.py
class MedicalVQA(Dataset):
"""Templated visual question answering over MedMNIST datasets, in the style of the MMBU challenge.
Every image yields a **modality** question; datasets with more than two classes add a **finding** question and a
**verification** of a named finding (true half of the time, drawn with ``seed``); datasets with malignant classes
add a **malignancy** question. Items are ``{"image", "caption", "question", "answer", "kind"}``.
``images`` holds every image once as uint8. After ``encode(encoder)``, items carry the encoder's cached outputs in
place of the images, so a frozen encoder runs once per image instead of once per question.
MMBU challenge: https://akiranishii.github.io/mmbu-challenge/
"""
KINDS = ("modality", "finding", "verification", "malignancy")
def __init__(
self,
names: list[str],
split: str = "train",
size: int = 64,
root: str | Path | None = None,
download: bool = True,
seed: int = 0,
):
self.sources = [MedMNIST(name, split, size, root, download) for name in names]
self.split = split
self.images: Tensor = torch.cat([s.images for s in self.sources])
self.features: Tensor | None = None
self.source = torch.cat([torch.full((len(s),), k) for k, s in enumerate(self.sources)])
self.captions, self.items = [], []
rng = random.Random(seed)
for k, s in enumerate(self.sources):
for label in s.labels.tolist():
image = len(self.captions)
self.captions.append(caption(s, label))
self.items += [(image, *qa) for qa in questions(s, label, rng)]
def __len__(self) -> int:
return len(self.items)
def __getitem__(self, i: int) -> dict:
image, kind, question, answer = self.items[i]
return {
"image": (self.images if self.features is None else self.features)[image],
"caption": self.captions[image],
"question": question,
"answer": answer,
"kind": kind,
}
@property
def info(self) -> str:
"""A table of the source datasets and of the questions of each kind."""
counts = [[0] * len(self.KINDS) for _ in self.sources]
for image, kind, *_ in self.items:
counts[self.source[image]][self.KINDS.index(kind)] += 1
head = f"{'dataset':13s}{'modality':24s}{'classes':>8s}{'images':>8s}" + "".join(
f"{k:>14s}" for k in self.KINDS
)
rows = [
f"{s.name:13s}{s.modality:24s}{len(s.classes):8d}{len(s):8d}" + "".join(f"{n:14d}" for n in c)
for s, c in zip(self.sources, counts)
]
total = f"{len(self.images)} images and {len(self)} questions ({self.split})"
return "\n".join([head, *rows, total])
def examples(self, per_source: int = 4) -> tuple[Tensor, list[str]]:
"""The first ``per_source`` images of each source dataset and their findings, for ``plots.images``."""
picks = [(s, i) for s in self.sources for i in range(min(per_source, len(s)))]
return torch.stack([s.images[i] for s, i in picks]), [s.classes[s.labels[i]] for s, i in picks]
def pixels(self, items: list[int]) -> Tensor:
"""The uint8 images of the given items."""
return self.images[[self.items[i][0] for i in items]]
@torch.no_grad()
def encode(self, encoder, batch_size: int = 512, dtype=torch.float16, device=None) -> "MedicalVQA":
"""Cache ``encoder(images)``, run on ``device`` (by default the encoder's); items then carry the outputs."""
device = device or next(encoder.parameters()).device
self.features = torch.cat([encoder(x.to(device)).to(dtype) for x in self.images.split(batch_size)])
return self
@property
def texts(self) -> list[str]:
"""Every caption, question and answer the templates can produce for these datasets."""
out = []
for s in self.sources:
for label in range(len(s.classes)):
out.append(caption(s, label))
out += [f"{q} {a}" for _, q, a in questions(s, label, None)]
return out
@property
def answers(self) -> list[str]:
"""The candidate answers for retrieval: every answer the templates can produce."""
return sorted({a for s in self.sources for label in range(len(s.classes)) for *_, a in questions(s, label)})
def weights(self) -> Tensor:
"""Per-item sampling weights that give each source dataset the same total weight."""
source = self.source[[image for image, *_ in self.items]]
return 1.0 / source.bincount()[source]property info
info: strA table of the source datasets and of the questions of each kind.
Source code in torch_world/datasets/medmnist.py
def info(self) -> str:
"""A table of the source datasets and of the questions of each kind."""
counts = [[0] * len(self.KINDS) for _ in self.sources]
for image, kind, *_ in self.items:
counts[self.source[image]][self.KINDS.index(kind)] += 1
head = f"{'dataset':13s}{'modality':24s}{'classes':>8s}{'images':>8s}" + "".join(
f"{k:>14s}" for k in self.KINDS
)
rows = [
f"{s.name:13s}{s.modality:24s}{len(s.classes):8d}{len(s):8d}" + "".join(f"{n:14d}" for n in c)
for s, c in zip(self.sources, counts)
]
total = f"{len(self.images)} images and {len(self)} questions ({self.split})"
return "\n".join([head, *rows, total])method examples
examples(per_source: int = 4) -> tuple[Tensor, list[str]]The first per_source images of each source dataset and their findings, for plots.images.
Source code in torch_world/datasets/medmnist.py
def examples(self, per_source: int = 4) -> tuple[Tensor, list[str]]:
"""The first ``per_source`` images of each source dataset and their findings, for ``plots.images``."""
picks = [(s, i) for s in self.sources for i in range(min(per_source, len(s)))]
return torch.stack([s.images[i] for s, i in picks]), [s.classes[s.labels[i]] for s, i in picks]method pixels
pixels(items: list[int]) -> TensorThe uint8 images of the given items.
Source code in torch_world/datasets/medmnist.py
def pixels(self, items: list[int]) -> Tensor:
"""The uint8 images of the given items."""
return self.images[[self.items[i][0] for i in items]]method encode
encode(
encoder, batch_size: int = 512, dtype=torch.float16, device=None
) -> MedicalVQACache encoder(images), run on device (by default the encoder's); items then carry the outputs.
Source code in torch_world/datasets/medmnist.py
@torch.no_grad()
def encode(self, encoder, batch_size: int = 512, dtype=torch.float16, device=None) -> "MedicalVQA":
"""Cache ``encoder(images)``, run on ``device`` (by default the encoder's); items then carry the outputs."""
device = device or next(encoder.parameters()).device
self.features = torch.cat([encoder(x.to(device)).to(dtype) for x in self.images.split(batch_size)])
return selfproperty texts
texts: list[str]Every caption, question and answer the templates can produce for these datasets.
Source code in torch_world/datasets/medmnist.py
def texts(self) -> list[str]:
"""Every caption, question and answer the templates can produce for these datasets."""
out = []
for s in self.sources:
for label in range(len(s.classes)):
out.append(caption(s, label))
out += [f"{q} {a}" for _, q, a in questions(s, label, None)]
return outproperty answers
answers: list[str]The candidate answers for retrieval: every answer the templates can produce.
Source code in torch_world/datasets/medmnist.py
def answers(self) -> list[str]:
"""The candidate answers for retrieval: every answer the templates can produce."""
return sorted({a for s in self.sources for label in range(len(s.classes)) for *_, a in questions(s, label)})method weights
weights() -> TensorPer-item sampling weights that give each source dataset the same total weight.
Source code in torch_world/datasets/medmnist.py
def weights(self) -> Tensor:
"""Per-item sampling weights that give each source dataset the same total weight."""
source = self.source[[image for image, *_ in self.items]]
return 1.0 / source.bincount()[source]