id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
20,187
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value if isinstance(value, int) else value.slvs_index return type_from_index(index) SEGMENT = (*LINE, *CURVE) def is_path(entity: EntityRef) -> bool: return _get_type(entity) in (*SEGMENT, SlvsCircle)
null
20,188
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value if isinstance(value, int) else value.slvs_index return type_from_index(index) def is_closed(entity: EntityRef) -> bool: return _get_type(entity) == SlvsCircle
null
20,189
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: def is_sketch(entity: EntityRef) -> bool: return _get_type(entity) == SlvsSketch
null
20,190
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value if isinstance(value, int) else value.slvs_index return type_from_index(index) def is_circle(entity: EntityRef) -> bool: return _get_type(entity) == SlvsCircle
null
20,191
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def slvs_entity_pointer(cls, name, **kwargs): index_prop = name + "_i" annotations = {} if hasattr(cls, "__annotations__"): annotations = cls.__annotations__.copy() annotations[index_prop] = IntProperty(name=name + " index", default=-1, **kwargs) setattr(cls, "__annotations__", annotations) @property def func(self): index = getattr(self, index_prop) return None if index == -1 else bpy.context.scene.sketcher.entities.get(index) setattr(cls, name, func) @func.setter def setter(self, entity): index = entity.slvs_index if entity else -1 setattr(self, index_prop, index) setattr(cls, name, setter)
null
20,192
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def tag_update(self, context: Context): self.tag_update()
null
20,193
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def round_v(vec, ndigits=None): values = [] for v in vec: values.append(round(v, ndigits=ndigits)) return Vector(values)
null
20,194
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def get_connection_point(seg_1, seg_2): points = seg_1.connection_points() for p in seg_2.connection_points(): if p in points: return p
null
20,195
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def get_bezier_curve_midpoint_positions( curve_element, segment_count, midpoints, angle, cyclic=False ): positions = [] if segment_count == 1: return [] if cyclic: point_count = segment_count else: point_count = segment_count - 1 a = angle / segment_count for i in range(point_count): pos = curve_element.point_on_curve(a * (i + 1)) positions.append(pos) return positions
null
20,196
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def create_bezier_curve( segment_count, bezier_points, locations, center, base_offset, invert=False, cyclic=False, ): if cyclic: bezier_points.append(bezier_points[0]) locations.append(locations[0]) for index in range(segment_count): loc1, loc2 = locations[index], locations[index + 1] b1, b2 = bezier_points[index], bezier_points[index + 1] coords = [] for i, loc in enumerate((loc1, loc2)): pos = loc - center angle = math.atan2(pos[1], pos[0]) offset = base_offset.copy() if i == 0 and invert or i == 1 and not invert: offset[1] *= -1 offset.rotate(Matrix.Rotation(angle, 2)) coords.append((center + offset).to_3d()) b1.handle_right = coords[0] b2.handle_left = coords[1] b2.co = loc2.to_3d()
null
20,197
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix POINT = (*POINT3D, *POINT2D) LINE = (SlvsLine3D, SlvsLine2D) CURVE = (SlvsCircle, SlvsArc) class SlvsWorkplane(SlvsGenericEntity, PropertyGroup): """Representation of a plane which is defined by an origin point and a normal. Workplanes are used to define the position of 2D entities which only store the coordinates on the plane. Arguments: p1 (SlvsPoint3D): Origin Point of the Plane nm (SlvsNormal3D): Normal which defines the orientation """ size = 0.4 def dependencies(self) -> List[SlvsGenericEntity]: return [self.p1, self.nm] def size(self): return preferences.get_prefs().workplane_size def update(self): if bpy.app.background: return p1, nm = self.p1, self.nm coords = draw_rect_2d(0, 0, self.size, self.size) coords = [(Vector(co))[:] for co in coords] indices = ((0, 1), (1, 2), (2, 3), (3, 0)) self._batch = batch_for_shader( self._shader, "LINES", {"pos": coords}, indices=indices ) self.is_dirty = False # NOTE: probably better to avoid overwriting draw func.. def draw(self, context): if not self.is_visible(context): return with gpu.matrix.push_pop(): scale = context.region_data.view_distance gpu.matrix.multiply_matrix(self.matrix_basis) gpu.matrix.scale(Vector((scale, scale, scale))) col = self.color(context) # Let parent draw outline super().draw(context) # Additionally draw a face col_surface = col[:-1] + (0.2,) shader = Shaders.uniform_color_3d() shader.bind() gpu.state.blend_set("ALPHA") shader.uniform_float("color", col_surface) coords = draw_rect_2d(0, 0, self.size, self.size) coords = [Vector(co)[:] for co in coords] indices = ((0, 1, 2), (0, 2, 3)) batch = batch_for_shader(shader, "TRIS", {"pos": coords}, indices=indices) batch.draw(shader) self.restore_opengl_defaults() def draw_id(self, context): with gpu.matrix.push_pop(): scale = context.region_data.view_distance gpu.matrix.multiply_matrix(self.matrix_basis) gpu.matrix.scale(Vector((scale, scale, scale))) super().draw_id(context) def create_slvs_data(self, solvesys, group=Solver.group_fixed): handle = solvesys.addWorkplane(self.p1.py_data, self.nm.py_data, group=group) self.py_data = handle def matrix_basis(self): mat_rot = self.nm.orientation.to_matrix().to_4x4() return Matrix.Translation(self.p1.location) @ mat_rot def normal(self): v = global_data.Z_AXIS.copy() quat = self.nm.orientation v.rotate(quat) return v def draw_props(self, layout): # Display the normals props as they're not drawn in the viewport sub = self.nm.draw_props(layout) sub.operator(Operators.AlignWorkplaneCursor).index = self.slvs_index return sub def make_coincident(solvesys, point_handle, e2, wp, group, entity_type=None): from .categories import LINE, CURVE, POINT from .workplane import SlvsWorkplane func = None set_wp = False if entity_type: handle = e2 else: entity_type = type(e2) handle = e2.py_data if entity_type in LINE: func = solvesys.addPointOnLine set_wp = True elif entity_type in CURVE: func = solvesys.addPointOnCircle elif entity_type == SlvsWorkplane: func = solvesys.addPointInPlane elif entity_type in POINT: func = solvesys.addPointsCoincident set_wp = True kwargs = { "group": group, } if set_wp: kwargs["wrkpln"] = wp return func(point_handle, handle, **kwargs)
null
20,198
import logging import math from bpy.types import PropertyGroup from bpy.props import BoolProperty, FloatProperty, EnumProperty from bpy.utils import register_classes_factory from mathutils import Vector, Matrix from mathutils.geometry import distance_point_to_plane, intersect_point_line from ..solver import Solver from ..utilities import preferences from ..global_data import WpReq from ..utilities.view import location_3d_to_region_2d from ..utilities.math import range_2pi from .base_constraint import DimensionalConstraint from .utilities import slvs_entity_pointer from .categories import POINT, LINE, POINT2D, CURVE from ..utilities.solver import update_system_cb from ..utilities.bpy import setprop, bpyEnum from .workplane import SlvsWorkplane from .point_3d import SlvsPoint3D from .line_3d import SlvsLine3D from .point_2d import SlvsPoint2D from .line_2d import SlvsLine2D from .arc import SlvsArc from .circle import SlvsCircle def get_side_of_line(line_start, line_end, point): line_end = line_end - line_start point = point - line_start return -( (line_end.x - line_start.x) * (point.y - line_start.y) - (line_end.y - line_start.y) * (point.x - line_start.x) )
null
20,199
import logging import math from bpy.types import PropertyGroup from bpy.props import BoolProperty, FloatProperty, EnumProperty from bpy.utils import register_classes_factory from mathutils import Vector, Matrix from mathutils.geometry import distance_point_to_plane, intersect_point_line from ..solver import Solver from ..utilities import preferences from ..global_data import WpReq from ..utilities.view import location_3d_to_region_2d from ..utilities.math import range_2pi from .base_constraint import DimensionalConstraint from .utilities import slvs_entity_pointer from .categories import POINT, LINE, POINT2D, CURVE from ..utilities.solver import update_system_cb from ..utilities.bpy import setprop, bpyEnum from .workplane import SlvsWorkplane from .point_3d import SlvsPoint3D from .line_3d import SlvsLine3D from .point_2d import SlvsPoint2D from .line_2d import SlvsLine2D from .arc import SlvsArc from .circle import SlvsCircle def _get_aligned_distance(p_1, p_2, alignment): if alignment == "HORIZONTAL": return abs(p_2.co.x - p_1.co.x) if alignment == "VERTICAL": return abs(p_2.co.y - p_1.co.y) return (p_2.co - p_1.co).length
null
20,200
import logging import math from bpy.types import PropertyGroup from bpy.props import BoolProperty, FloatProperty, EnumProperty from bpy.utils import register_classes_factory from mathutils import Vector, Matrix from mathutils.geometry import distance_point_to_plane, intersect_point_line from ..solver import Solver from ..utilities import preferences from ..global_data import WpReq from ..utilities.view import location_3d_to_region_2d from ..utilities.math import range_2pi from .base_constraint import DimensionalConstraint from .utilities import slvs_entity_pointer from .categories import POINT, LINE, POINT2D, CURVE from ..utilities.solver import update_system_cb from ..utilities.bpy import setprop, bpyEnum from .workplane import SlvsWorkplane from .point_3d import SlvsPoint3D from .line_3d import SlvsLine3D from .point_2d import SlvsPoint2D from .line_2d import SlvsLine2D from .arc import SlvsArc from .circle import SlvsCircle def _get_value(self): if self.is_reference: val = self.init_props(align=self.align)["value"] return self.to_displayed_value(val) if self.get("value") is None: self.assign_init_props() return self.to_displayed_value(self["value"])
null
20,201
import logging from typing import List import bpy from bpy.types import PropertyGroup, Context from bpy.props import BoolProperty from gpu_extras.batch import batch_for_shader import math from mathutils import Vector, Matrix from mathutils.geometry import intersect_line_sphere_2d, intersect_sphere_sphere_2d from bpy.utils import register_classes_factory from ..solver import Solver from .base_entity import SlvsGenericEntity from .base_entity import Entity2D from .utilities import slvs_entity_pointer, tag_update from .constants import CURVE_RESOLUTION from ..utilities.constants import HALF_TURN, FULL_TURN, QUARTER_TURN from ..utilities.math import range_2pi, pol2cart from ..utilities.draw import coords_arc_2d from .utilities import ( get_connection_point, get_bezier_curve_midpoint_positions, create_bezier_curve, round_v, ) from ..utilities.math import range_2pi, pol2cart def range_2pi(angle: float) -> float: """Map angle range -Pi/+Pi to 0/2*Pi""" return (angle + FULL_TURN) % FULL_TURN def _get_angle(start, end): return range_2pi(math.atan2(end[1], end[0]) - math.atan2(start[1], start[0]))
null
20,202
import logging from typing import Union, Generator import bpy from bpy.types import PropertyGroup, Context from bpy.utils import register_class, unregister_class from bpy.props import IntProperty, BoolProperty, PointerProperty, IntVectorProperty from .. import global_data from ..solver import solve_system from .utilities import slvs_entity_pointer from .base_entity import SlvsGenericEntity from .group_entities import SlvsEntities from .group_constraints import SlvsConstraints from ..utilities.view import update_cb class SketcherProps(PropertyGroup): """The base structure for CAD Sketcher""" entities: PointerProperty(type=SlvsEntities) constraints: PointerProperty(type=SlvsConstraints) show_origin: BoolProperty(name="Show Origin Entities") use_construction: BoolProperty( name="Construction Mode", description="Draw all subsequent entities in construction mode", default=False, options={"SKIP_SAVE"}, update=update_cb, ) selectable_constraints: BoolProperty( name="Constraints Selectability", default=True, options={"SKIP_SAVE"}, update=update_cb, ) version: IntVectorProperty( name="Addon Version", description="CAD Sketcher addon version this scene was saved with", ) # This is needed for the sketches ui list ui_active_sketch: IntProperty() def all(self) -> Generator[Union[SlvsGenericEntity, SlvsConstraints], None, None]: """Iterate over entities and constraints of every type""" for entity in self.entities.all: yield entity for constraint in self.constraints.all: yield constraint def solve(self, context: Context): return solve_system(context) def purge_stale_data(self): global_data.hover = -1 global_data.selected.clear() global_data.batches.clear() for e in self.entities.all: e.dirty = True def register(): register_class(SketcherProps) bpy.types.Scene.sketcher = PointerProperty(type=SketcherProps) bpy.types.Object.sketch_index = IntProperty(name="Parent Sketch", default=-1)
null
20,203
import logging from typing import Union, Generator import bpy from bpy.types import PropertyGroup, Context from bpy.utils import register_class, unregister_class from bpy.props import IntProperty, BoolProperty, PointerProperty, IntVectorProperty from .. import global_data from ..solver import solve_system from .utilities import slvs_entity_pointer from .base_entity import SlvsGenericEntity from .group_entities import SlvsEntities from .group_constraints import SlvsConstraints from ..utilities.view import update_cb class SketcherProps(PropertyGroup): """The base structure for CAD Sketcher""" entities: PointerProperty(type=SlvsEntities) constraints: PointerProperty(type=SlvsConstraints) show_origin: BoolProperty(name="Show Origin Entities") use_construction: BoolProperty( name="Construction Mode", description="Draw all subsequent entities in construction mode", default=False, options={"SKIP_SAVE"}, update=update_cb, ) selectable_constraints: BoolProperty( name="Constraints Selectability", default=True, options={"SKIP_SAVE"}, update=update_cb, ) version: IntVectorProperty( name="Addon Version", description="CAD Sketcher addon version this scene was saved with", ) # This is needed for the sketches ui list ui_active_sketch: IntProperty() def all(self) -> Generator[Union[SlvsGenericEntity, SlvsConstraints], None, None]: """Iterate over entities and constraints of every type""" for entity in self.entities.all: yield entity for constraint in self.constraints.all: yield constraint def solve(self, context: Context): return solve_system(context) def purge_stale_data(self): global_data.hover = -1 global_data.selected.clear() global_data.batches.clear() for e in self.entities.all: e.dirty = True def unregister(): del bpy.types.Object.sketch_index del bpy.types.Scene.sketcher unregister_class(SketcherProps)
null
20,204
import bpy import logging from bpy.app.handlers import persistent def register_handlers(): def _setup_builtin_handlers(): def register(): _setup_builtin_handlers() register_handlers()
null
20,205
import bpy import logging from bpy.app.handlers import persistent def unregister_handlers(): global _builtin_handlers for handler_name in _builtin_handlers.keys(): msg = "Remove <{}> builtin handlers: ".format(handler_name) for cb in _builtin_handlers[handler_name]: handler_list = getattr(bpy.app.handlers, handler_name) if cb not in handler_list: continue msg += "\n - {}".format(cb.__name__) handler_list.remove(cb) logger.debug(msg) def unregister(): unregister_handlers()
null
20,207
def apply_with_stopping_condition( module, apply_fn, apply_condition=None, stopping_condition=None, **other_args ): if stopping_condition(module): return if apply_condition(module): apply_fn(module, **other_args) for child in module.children(): apply_with_stopping_condition( child, apply_fn, apply_condition=apply_condition, stopping_condition=stopping_condition, **other_args )
null
20,210
from typing import Optional from transformers import AutoModelForCausalLM, AutoTokenizer import open_clip from .flamingo import Flamingo from .flamingo_lm import FlamingoLMMixin from .utils import extend_instance def _infer_decoder_layers_attr_name(model): for k in __KNOWN_DECODER_LAYERS_ATTR_NAMES: if k.lower() in model.__class__.__name__.lower(): return __KNOWN_DECODER_LAYERS_ATTR_NAMES[k] raise ValueError( f"We require the attribute name for the nn.ModuleList in the decoder storing the transformer block layers. Please supply this string manually." ) class Flamingo(nn.Module): def __init__( self, vision_encoder: nn.Module, lang_encoder: nn.Module, eoc_token_id: int, media_token_id: int, vis_dim: int, cross_attn_every_n_layers: int = 1, gradient_checkpointing: bool = False, ): """ Args: vision_encoder (nn.Module): HF CLIPModel lang_encoder (nn.Module): HF causal language model eoc_token_id (int): Token id for <|endofchunk|> media_token_id (int): Token id for <image> vis_dim (int): Dimension of the visual features. Visual features are projected to match this shape along the last dimension. cross_attn_every_n_layers (int, optional): How often to apply cross attention after transformer layer. Defaults to 1. """ super().__init__() self.eoc_token_id = eoc_token_id self.media_token_id = media_token_id self.vis_dim = vis_dim if hasattr(lang_encoder.config, "d_model"): self.lang_dim = lang_encoder.config.d_model # mpt uses d_model else: self.lang_dim = lang_encoder.config.hidden_size self.vision_encoder = vision_encoder.visual self.perceiver = PerceiverResampler(dim=self.vis_dim) self.lang_encoder = lang_encoder self.lang_encoder.init_flamingo( media_token_id=media_token_id, lang_hidden_size=self.lang_dim, vis_hidden_size=self.vis_dim, cross_attn_every_n_layers=cross_attn_every_n_layers, gradient_checkpointing=gradient_checkpointing, ) self._use_gradient_checkpointing = gradient_checkpointing self.perceiver._use_gradient_checkpointing = gradient_checkpointing def forward( self, vision_x: torch.Tensor, lang_x: torch.Tensor, attention_mask: torch.Tensor = None, labels: torch.Tensor = None, clear_conditioned_layers: bool = True, past_key_values=None, use_cache: bool = False, ): """ Forward pass of Flamingo. Args: vision_x (torch.Tensor): Vision input shape (B, T_img, F, C, H, W) with F=1 lang_x (torch.Tensor): Language input ids shape (B, T_txt) attention_mask (torch.Tensor, optional): Attention mask. Defaults to None. labels (torch.Tensor, optional): Labels. Defaults to None. clear_conditioned_layers: if True, clear the conditioned layers once the foward pass is completed. Set this to false if the same set of images will be reused in another subsequent forward pass. past_key_values: pre-computed values to pass to language model. See past_key_values documentation in Hugging Face CausalLM models. use_cache: whether to use cached key values. See use_cache documentation in Hugging Face CausalLM models. """ assert ( self.lang_encoder.initialized_flamingo ), "Flamingo layers are not initialized. Please call `init_flamingo` first." assert ( self.lang_encoder._use_cached_vision_x or vision_x is not None ), "Must provide either vision_x or have precached media using cache_media()." if self.lang_encoder._use_cached_vision_x: # Case: use cached; vision_x should be cached and other # vision-related inputs should not be provided. assert ( vision_x is None ), "Expect vision_x to be None when media has been cached using cache_media(). Try uncache_media() first." assert self.lang_encoder.is_conditioned() else: # Case: do not use caching (i.e. this is a standard forward pass); self._encode_vision_x(vision_x=vision_x) self._condition_media_locations(input_ids=lang_x) output = self.lang_encoder( input_ids=lang_x, attention_mask=attention_mask, labels=labels, past_key_values=past_key_values, use_cache=use_cache, ) if clear_conditioned_layers: self.lang_encoder.clear_conditioned_layers() return output def generate( self, vision_x: torch.Tensor, lang_x: torch.Tensor, attention_mask: torch.Tensor = None, **kwargs, ): """ Generate text conditioned on vision and language inputs. Args: vision_x (torch.Tensor): Vision input shape (B, T_img, F, C, H, W) images in the same chunk are collated along T_img, and frames are collated along F currently only F=1 is supported (single-frame videos) lang_x (torch.Tensor): Language input shape (B, T_txt) **kwargs: see generate documentation in Hugging Face CausalLM models. Some notable kwargs: max_length (int, optional): Maximum length of the output. Defaults to None. attention_mask (torch.Tensor, optional): Attention mask. Defaults to None. num_beams (int, optional): Number of beams. Defaults to 1. max_new_tokens (int, optional): Maximum new tokens. Defaults to None. temperature (float, optional): Temperature. Defaults to 1.0. top_k (int, optional): Top k. Defaults to 50. top_p (float, optional): Top p. Defaults to 1.0. no_repeat_ngram_size (int, optional): No repeat ngram size. Defaults to 0. length_penalty (float, optional): Length penalty. Defaults to 1.0. num_return_sequences (int, optional): Number of return sequences. Defaults to 1. do_sample (bool, optional): Do sample. Defaults to False. early_stopping (bool, optional): Early stopping. Defaults to False. Returns: torch.Tensor: lang_x with generated tokens appended to it """ num_beams = kwargs.pop("num_beams", 1) if num_beams > 1: vision_x = vision_x.repeat_interleave(num_beams, dim=0) self.lang_encoder._use_cached_vision_x = True self._encode_vision_x(vision_x=vision_x) eos_token_id = kwargs.pop("eos_token_id", self.eoc_token_id) output = self.lang_encoder.generate( input_ids=lang_x, attention_mask=attention_mask, eos_token_id=eos_token_id, num_beams=num_beams, **kwargs, ) self.lang_encoder.clear_conditioned_layers() self.lang_encoder._use_cached_vision_x = False return output def _encode_vision_x(self, vision_x: torch.Tensor): """ Compute media tokens from vision input by passing it through vision encoder and conditioning language model. Args: vision_x (torch.Tensor): Vision input shape (B, T_img, F, C, H, W) Images in the same chunk are collated along T_img, and frames are collated along F Currently only F=1 is supported (single-frame videos) rearrange code based on https://github.com/dhansmair/flamingo-mini """ assert vision_x.ndim == 6, "vision_x should be of shape (b, T_img, F, C, H, W)" b, T, F = vision_x.shape[:3] assert F == 1, "Only single frame supported" vision_x = rearrange(vision_x, "b T F c h w -> (b T F) c h w") with torch.no_grad(): vision_x = self.vision_encoder(vision_x)[1] vision_x = rearrange(vision_x, "(b T F) v d -> b T F v d", b=b, T=T, F=F) vision_x = self.perceiver(vision_x) for layer in self.lang_encoder._get_decoder_layers(): layer.condition_vis_x(vision_x) def wrap_fsdp(self, wrapper_kwargs, device_id): """ Manually wraps submodules for FSDP and move other parameters to device_id. Why manually wrap? - all parameters within the FSDP wrapper must have the same requires_grad. We have a mix of frozen and unfrozen parameters. - model.vision_encoder.visual needs to be individually wrapped or encode_vision_x errors See: https://github.com/pytorch/pytorch/issues/82461#issuecomment-1269136344 The rough wrapping structure is: - FlamingoModel - FSDP(FSDP(vision_encoder)) - FSDP(FSDP(perceiver)) - lang_encoder - FSDP(FSDP(input_embeddings)) - FlamingoLayers - FSDP(FSDP(gated_cross_attn_layer)) - FSDP(FSDP(decoder_layer)) - FSDP(FSDP(output_embeddings)) - other parameters Known issues: - Our FSDP strategy is not compatible with tied embeddings. If the LM embeddings are tied, train with DDP or set the --freeze_lm_embeddings flag to true. - With FSDP + gradient ckpting, one can increase the batch size with seemingly no upper bound. Although the training curves look okay, we found that downstream performance dramatically degrades if the batch size is unreasonably large (e.g., 100 MMC4 batch size for OPT-125M). FAQs about our FSDP wrapping strategy: Why double wrap? As of torch==2.0.1, FSDP's _post_forward_hook and _post_backward_hook only free gathered parameters if the module is NOT FSDP root. Why unfreeze the decoder_layers? See https://github.com/pytorch/pytorch/issues/95805 As of torch==2.0.1, FSDP's _post_backward_hook is only registed if the flat param requires_grad=True. We need the postback to fire to avoid OOM. To effectively freeze the decoder layers, we exclude them from the optimizer. What is assumed to be frozen v. unfrozen? We assume that the model is being trained under normal Flamingo settings with these lines being called in factory.py: ``` # Freeze all parameters model.requires_grad_(False) assert sum(p.numel() for p in model.parameters() if p.requires_grad) == 0 # Unfreeze perceiver, gated_cross_attn_layers, and LM input embeddings model.perceiver.requires_grad_(True) model.lang_encoder.gated_cross_attn_layers.requires_grad_(True) [optional] model.lang_encoder.get_input_embeddings().requires_grad_(True) ``` """ # unfreeze the decoder layers for block in self.lang_encoder.old_decoder_blocks: block.requires_grad_(True) # wrap in FSDP with enable_wrap(wrapper_cls=FSDP, **wrapper_kwargs): self.perceiver = wrap(wrap(self.perceiver)) self.lang_encoder.old_decoder_blocks = nn.ModuleList( wrap(wrap(block)) for block in self.lang_encoder.old_decoder_blocks ) self.lang_encoder.gated_cross_attn_layers = nn.ModuleList( wrap(wrap(layer)) if layer is not None else None for layer in self.lang_encoder.gated_cross_attn_layers ) self.lang_encoder.init_flamingo_layers(self._use_gradient_checkpointing) self.lang_encoder.set_input_embeddings( wrap(wrap(self.lang_encoder.get_input_embeddings())) ) self.lang_encoder.set_output_embeddings( wrap(wrap(self.lang_encoder.get_output_embeddings())) ) self.vision_encoder = wrap(wrap(self.vision_encoder)) # frozen # manually move non-FSDP managed parameters to device_id # these are all in lang_encoder apply_with_stopping_condition( module=self.lang_encoder, apply_fn=lambda m: m.to(device_id), apply_condition=lambda m: len(list(m.children())) == 0, stopping_condition=lambda m: isinstance(m, FSDP), ) # exclude the original decoder layers from the optimizer for block in self.lang_encoder.old_decoder_blocks: for p in block.parameters(): p.exclude_from_optimizer = True # set up clip_grad_norm_ function def clip_grad_norm_(max_norm): self.perceiver.clip_grad_norm_(max_norm) for layer in self.lang_encoder.gated_cross_attn_layers: if layer is not None: layer.clip_grad_norm_(max_norm) self.lang_encoder.get_input_embeddings().clip_grad_norm_(max_norm) self.clip_grad_norm_ = clip_grad_norm_ def _condition_media_locations(self, input_ids: torch.Tensor): """ Compute the media token locations from lang_x and condition the language model on these. Args: input_ids (torch.Tensor): Language input shape (B, T_txt) """ media_locations = input_ids == self.media_token_id for layer in self.lang_encoder._get_decoder_layers(): layer.condition_media_locations(media_locations) def cache_media(self, input_ids: torch.Tensor, vision_x: torch.Tensor): """ Pre-cache a prompt/sequence of images / text for log-likelihood evaluations. All subsequent calls to forward() will generate attending to the LAST image in vision_x. This is not meant to be used to cache things for generate(). Args: input_ids (torch.Tensor): Language input shape (B, T_txt) vision_x (torch.Tensor): Vision input shape (B, T_img, F, C, H, W) Images in the same chunk are collated along T_img, and frames are collated along F Currently only F=1 is supported (single-frame videos) """ self._encode_vision_x(vision_x=vision_x) self._condition_media_locations(input_ids=input_ids) self.lang_encoder._use_cached_vision_x = True def uncache_media(self): """ Clear all conditioning. """ self.lang_encoder.clear_conditioned_layers() self.lang_encoder._use_cached_vision_x = False class FlamingoLMMixin(nn.Module): """ Mixin to add cross-attention layers to a language model. """ def set_decoder_layers_attr_name(self, decoder_layers_attr_name): self.decoder_layers_attr_name = decoder_layers_attr_name def _get_decoder_layers(self): return getattr_recursive(self, self.decoder_layers_attr_name) def _set_decoder_layers(self, value): setattr_recursive(self, self.decoder_layers_attr_name, value) def init_flamingo( self, media_token_id, lang_hidden_size, vis_hidden_size, cross_attn_every_n_layers, gradient_checkpointing, ): """ Initialize Flamingo by adding a new gated cross attn to the decoder. Store the media token id for computing the media locations. """ self.old_decoder_blocks = self._get_decoder_layers() self.gated_cross_attn_layers = nn.ModuleList( [ GatedCrossAttentionBlock( dim=lang_hidden_size, dim_visual=vis_hidden_size ) if (layer_idx + 1) % cross_attn_every_n_layers == 0 else None for layer_idx, _ in enumerate(self._get_decoder_layers()) ] ) self.init_flamingo_layers(gradient_checkpointing) self.media_token_id = media_token_id self.initialized_flamingo = True self._use_cached_vision_x = False def init_flamingo_layers(self, gradient_checkpointing): """ Re initializes the FlamingoLayers. Propagates any changes made to self.gated_corss_attn_layers or self.old_decoder_blocks """ self._set_decoder_layers( nn.ModuleList( [ FlamingoLayer( gated_cross_attn_layer, decoder_layer, gradient_checkpointing ) for gated_cross_attn_layer, decoder_layer in zip( self.gated_cross_attn_layers, self.old_decoder_blocks ) ] ) ) def forward(self, input_ids, attention_mask, **kwargs): """Condition the Flamingo layers on the media locations before forward()""" if not self.initialized_flamingo: raise ValueError( "Flamingo layers are not initialized. Please call `init_flamingo` first." ) media_locations = input_ids == self.media_token_id # if there are media already cached and we're generating and there are no media tokens in the input, # we'll assume that ALL input tokens should attend to the last previous media that is cached. # this is especially important for HF generate() compatibility, since generate() calls forward() # repeatedly one token at a time (with no media tokens). # without this check, the model would not attend to any images when generating (after the first token) use_cached_media_locations = ( self._use_cached_vision_x and self.is_conditioned() and not media_locations.any() ) for layer in self._get_decoder_layers(): if not use_cached_media_locations: layer.condition_media_locations(media_locations) layer.condition_use_cached_media(use_cached_media_locations) # package arguments for the other parent's forward. since we don't know the order of the arguments, # make them all kwargs kwargs["input_ids"] = input_ids kwargs["attention_mask"] = attention_mask return super().forward(**kwargs) # Call the other parent's forward method def is_conditioned(self) -> bool: """Check whether all decoder layers are already conditioned.""" return all(l.is_conditioned() for l in self._get_decoder_layers()) def clear_conditioned_layers(self): for layer in self._get_decoder_layers(): layer.condition_vis_x(None) layer.condition_media_locations(None) layer.condition_use_cached_media(None) def extend_instance(obj, mixin): """Apply mixins to a class instance after creation""" base_cls = obj.__class__ base_cls_name = obj.__class__.__name__ obj.__class__ = type( base_cls_name, (mixin, base_cls), {} ) # mixin needs to go first for our forward() logic to work The provided code snippet includes necessary dependencies for implementing the `create_model_and_transforms` function. Write a Python function `def create_model_and_transforms( clip_vision_encoder_path: str, clip_vision_encoder_pretrained: str, lang_encoder_path: str, tokenizer_path: str, cross_attn_every_n_layers: int = 1, use_local_files: bool = False, decoder_layers_attr_name: str = None, freeze_lm_embeddings: bool = False, cache_dir: Optional[str] = None, **flamingo_kwargs, )` to solve the following problem: Initialize a Flamingo model from a pretrained vision encoder and language encoder. Appends special tokens to the tokenizer and freezes backbones. Args: clip_vision_encoder_path (str): path to pretrained clip model (e.g. "ViT-B-32") clip_vision_encoder_pretrained (str): name of pretraining dataset for clip model (e.g. "laion2b_s32b_b79k") lang_encoder_path (str): path to pretrained language encoder tokenizer_path (str): path to pretrained tokenizer cross_attn_every_n_layers (int, optional): determines how often to add a cross-attention layer. Defaults to 1. use_local_files (bool, optional): whether to use local files. Defaults to False. decoder_layers_attr_name (str, optional): name of the decoder layers attribute. Defaults to None. freeze_lm_embeddings (bool, optional): whether to freeze LM input embeddings when configuring Perceiver. cache_dir (str, optional): path to cache directory for downloading OpenClip/HF weights. Returns: Flamingo: Flamingo model from pretrained vision and language encoders Image processor: Pipeline to preprocess input images Tokenizer: A tokenizer for the language model Here is the function: def create_model_and_transforms( clip_vision_encoder_path: str, clip_vision_encoder_pretrained: str, lang_encoder_path: str, tokenizer_path: str, cross_attn_every_n_layers: int = 1, use_local_files: bool = False, decoder_layers_attr_name: str = None, freeze_lm_embeddings: bool = False, cache_dir: Optional[str] = None, **flamingo_kwargs, ): """ Initialize a Flamingo model from a pretrained vision encoder and language encoder. Appends special tokens to the tokenizer and freezes backbones. Args: clip_vision_encoder_path (str): path to pretrained clip model (e.g. "ViT-B-32") clip_vision_encoder_pretrained (str): name of pretraining dataset for clip model (e.g. "laion2b_s32b_b79k") lang_encoder_path (str): path to pretrained language encoder tokenizer_path (str): path to pretrained tokenizer cross_attn_every_n_layers (int, optional): determines how often to add a cross-attention layer. Defaults to 1. use_local_files (bool, optional): whether to use local files. Defaults to False. decoder_layers_attr_name (str, optional): name of the decoder layers attribute. Defaults to None. freeze_lm_embeddings (bool, optional): whether to freeze LM input embeddings when configuring Perceiver. cache_dir (str, optional): path to cache directory for downloading OpenClip/HF weights. Returns: Flamingo: Flamingo model from pretrained vision and language encoders Image processor: Pipeline to preprocess input images Tokenizer: A tokenizer for the language model """ vision_encoder, _, image_processor = open_clip.create_model_and_transforms( clip_vision_encoder_path, pretrained=clip_vision_encoder_pretrained, cache_dir=cache_dir, ) # set the vision encoder to output the visual features vision_encoder.visual.output_tokens = True text_tokenizer = AutoTokenizer.from_pretrained( tokenizer_path, local_files_only=use_local_files, trust_remote_code=True, cache_dir=cache_dir, ) # add Flamingo special tokens to the tokenizer text_tokenizer.add_special_tokens( {"additional_special_tokens": ["<|endofchunk|>", "<image>"]} ) if text_tokenizer.pad_token is None: # Issue: GPT models don't have a pad token, which we use to # modify labels for the loss. text_tokenizer.add_special_tokens({"pad_token": "<PAD>"}) lang_encoder = AutoModelForCausalLM.from_pretrained( lang_encoder_path, local_files_only=use_local_files, trust_remote_code=True, cache_dir=cache_dir, ) # hacks for MPT-1B, which doesn't have a get_input_embeddings method if "mpt-1b-redpajama-200b" in lang_encoder_path: class EmbeddingFnMixin: def get_input_embeddings(self): return self.transformer.wte def set_input_embeddings(self, new_embeddings): self.transformer.wte = new_embeddings extend_instance(lang_encoder, EmbeddingFnMixin) # convert LM to FlamingoLM extend_instance(lang_encoder, FlamingoLMMixin) if decoder_layers_attr_name is None: decoder_layers_attr_name = _infer_decoder_layers_attr_name(lang_encoder) lang_encoder.set_decoder_layers_attr_name(decoder_layers_attr_name) lang_encoder.resize_token_embeddings(len(text_tokenizer)) model = Flamingo( vision_encoder, lang_encoder, text_tokenizer.encode("<|endofchunk|>")[-1], text_tokenizer.encode("<image>")[-1], vis_dim=open_clip.get_model_config(clip_vision_encoder_path)["vision_cfg"][ "width" ], cross_attn_every_n_layers=cross_attn_every_n_layers, **flamingo_kwargs, ) # Freeze all parameters model.requires_grad_(False) assert sum(p.numel() for p in model.parameters() if p.requires_grad) == 0 # Unfreeze perceiver, gated_cross_attn_layers, and LM input embeddings model.perceiver.requires_grad_(True) model.lang_encoder.gated_cross_attn_layers.requires_grad_(True) if not freeze_lm_embeddings: model.lang_encoder.get_input_embeddings().requires_grad_(True) # TODO: investigate also training the output embeddings when untied print( f"Flamingo model initialized with {sum(p.numel() for p in model.parameters() if p.requires_grad)} trainable parameters" ) return model, image_processor, text_tokenizer
Initialize a Flamingo model from a pretrained vision encoder and language encoder. Appends special tokens to the tokenizer and freezes backbones. Args: clip_vision_encoder_path (str): path to pretrained clip model (e.g. "ViT-B-32") clip_vision_encoder_pretrained (str): name of pretraining dataset for clip model (e.g. "laion2b_s32b_b79k") lang_encoder_path (str): path to pretrained language encoder tokenizer_path (str): path to pretrained tokenizer cross_attn_every_n_layers (int, optional): determines how often to add a cross-attention layer. Defaults to 1. use_local_files (bool, optional): whether to use local files. Defaults to False. decoder_layers_attr_name (str, optional): name of the decoder layers attribute. Defaults to None. freeze_lm_embeddings (bool, optional): whether to freeze LM input embeddings when configuring Perceiver. cache_dir (str, optional): path to cache directory for downloading OpenClip/HF weights. Returns: Flamingo: Flamingo model from pretrained vision and language encoders Image processor: Pipeline to preprocess input images Tokenizer: A tokenizer for the language model
20,211
import argparse import glob import os import random import numpy as np import torch import wandb from data import get_data from distributed import init_distributed_device, world_info_from_env from torch.nn.parallel import DistributedDataParallel as DDP from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from train_utils import ( train_one_epoch, get_mp_policy_dtype, save_checkpoint, ) from transformers import ( get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_linear_schedule_with_warmup, ) from torch.distributed.fsdp import ( CPUOffload, MixedPrecision, ShardingStrategy, BackwardPrefetch, ) from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( checkpoint_wrapper, CheckpointWrapper, CheckpointImpl, apply_activation_checkpointing, ) from torch.distributed.fsdp._init_utils import _init_intra_and_inter_node_groups from torch.distributed.distributed_c10d import _get_default_group import functools from open_flamingo import create_model_and_transforms def random_seed(seed=42, rank=0): torch.manual_seed(seed + rank) np.random.seed(seed + rank) random.seed(seed + rank)
null
20,212
import ast import json import logging import os import random import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import webdataset as wds from PIL import Image from torch.utils.data import DataLoader, IterableDataset, get_worker_info from torch.utils.data.distributed import DistributedSampler from webdataset.filters import _shuffle from webdataset.tariterators import ( base_plus_ext, tar_file_expander, url_opener, valid_sample, ) def get_dataset_size(shards): shards_list = list(braceexpand.braceexpand(shards)) dir_path = os.path.dirname(shards[0]) sizes_filename = os.path.join(dir_path, "sizes.json") len_filename = os.path.join(dir_path, "__len__") if os.path.exists(sizes_filename): sizes = json.load(open(sizes_filename, "r")) total_size = sum( [ int(sizes[os.path.basename(shard)]) if os.path.basename(shard) in sizes else 0 for shard in shards_list ] ) elif os.path.exists(len_filename): # FIXME this used to be eval(open(...)) but that seemed rather unsafe total_size = ast.literal_eval(open(len_filename, "r").read()) else: total_size = None # num samples undefined # some common dataset sizes (at time of authors last download) # CC3M (train): 2905954 # CC12M: 10968539 # LAION-400M: 407332084 # LAION-2B (english): 2170337258 num_shards = len(shards_list) return total_size, num_shards
null
20,213
import ast import json import logging import os import random import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import webdataset as wds from PIL import Image from torch.utils.data import DataLoader, IterableDataset, get_worker_info from torch.utils.data.distributed import DistributedSampler from webdataset.filters import _shuffle from webdataset.tariterators import ( base_plus_ext, tar_file_expander, url_opener, valid_sample, ) def count_samples(dataloader): os.environ["WDS_EPOCH"] = "0" n_elements, n_batches = 0, 0 for images, texts in dataloader: n_batches += 1 n_elements += len(images) assert len(images) == len(texts) return n_elements, n_batches
null
20,214
import ast import json import logging import os import random import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import webdataset as wds from PIL import Image from torch.utils.data import DataLoader, IterableDataset, get_worker_info from torch.utils.data.distributed import DistributedSampler from webdataset.filters import _shuffle from webdataset.tariterators import ( base_plus_ext, tar_file_expander, url_opener, valid_sample, ) def log_and_continue(exn): """Call in an exception handler to ignore any exception, issue a warning, and continue.""" logging.warning(f"Handling webdataset error ({repr(exn)}). Ignoring.") return True def group_by_keys_nothrow( data, keys=base_plus_ext, lcase=True, suffixes=None, handler=None ): """Return function over iterator that groups key, value pairs into samples. :param keys: function that splits the key into key and extension (base_plus_ext) :param lcase: convert suffixes to lower case (Default value = True) """ current_sample = None for filesample in data: assert isinstance(filesample, dict) fname, value = filesample["fname"], filesample["data"] prefix, suffix = keys(fname) if prefix is None: continue if lcase: suffix = suffix.lower() # FIXME webdataset version throws if suffix in current_sample, but we have a potential for # this happening in the current LAION400m dataset if a tar ends with same prefix as the next # begins, rare, but can happen since prefix aren't unique across tar files in that dataset if ( current_sample is None or prefix != current_sample["__key__"] or suffix in current_sample ): if valid_sample(current_sample): yield current_sample current_sample = dict(__key__=prefix, __url__=filesample["__url__"]) if suffixes is None or suffix in suffixes: current_sample[suffix] = value if valid_sample(current_sample): yield current_sample def tarfile_to_samples_nothrow(src, handler=log_and_continue): # NOTE this is a re-impl of the webdataset impl with group_by_keys that doesn't throw streams = url_opener(src, handler=handler) files = tar_file_expander(streams, handler=handler) samples = group_by_keys_nothrow(files, handler=handler) return samples
null
20,215
import ast import json import logging import os import random import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import webdataset as wds from PIL import Image from torch.utils.data import DataLoader, IterableDataset, get_worker_info from torch.utils.data.distributed import DistributedSampler from webdataset.filters import _shuffle from webdataset.tariterators import ( base_plus_ext, tar_file_expander, url_opener, valid_sample, ) The provided code snippet includes necessary dependencies for implementing the `pytorch_worker_seed` function. Write a Python function `def pytorch_worker_seed(increment=0)` to solve the following problem: get dataloader worker seed from pytorch Here is the function: def pytorch_worker_seed(increment=0): """get dataloader worker seed from pytorch""" worker_info = get_worker_info() if worker_info is not None: # favour using the seed already created for pytorch dataloader workers if it exists seed = worker_info.seed if increment: # space out seed increments so they can't overlap across workers in different iterations seed += increment * max(1, worker_info.num_workers) return seed # fallback to wds rank based seed return wds.utils.pytorch_worker_seed()
get dataloader worker seed from pytorch
20,216
import functools import io import json import math import re import random import numpy as np import torch import torchvision import webdataset as wds from PIL import Image import base64 from scipy.optimize import linear_sum_assignment from data_utils import * def get_dataset_fn(dataset_type): """ Helper function to get the dataset function based on the dataset type """ if dataset_type == "image_text": return get_laion_dataset elif dataset_type == "mmc4": return get_mmc4_dataset else: raise ValueError(f"Unsupported dataset type: {dataset_type}") The provided code snippet includes necessary dependencies for implementing the `get_data` function. Write a Python function `def get_data(args, image_processor, tokenizer, dataset_type, epoch=0)` to solve the following problem: Interface for getting the webdatasets Here is the function: def get_data(args, image_processor, tokenizer, dataset_type, epoch=0): """ Interface for getting the webdatasets """ return get_dataset_fn(dataset_type)( args, image_processor=image_processor, epoch=epoch, tokenizer=tokenizer )
Interface for getting the webdatasets
20,218
import os import torch def is_using_horovod(): # NOTE w/ horovod run, OMPI vars should be set, but w/ SLURM PMI vars will be set # Differentiating between horovod and DDP use via SLURM may not be possible, so horovod arg still required... ompi_vars = ["OMPI_COMM_WORLD_RANK", "OMPI_COMM_WORLD_SIZE"] pmi_vars = ["PMI_RANK", "PMI_SIZE"] if all([var in os.environ for var in ompi_vars]) or all( [var in os.environ for var in pmi_vars] ): return True else: return False
null
20,219
import os import torch try: import horovod.torch as hvd except ImportError: hvd = None def is_using_distributed(): if "WORLD_SIZE" in os.environ: return int(os.environ["WORLD_SIZE"]) > 1 if "SLURM_NTASKS" in os.environ: return int(os.environ["SLURM_NTASKS"]) > 1 return False def world_info_from_env(): local_rank = 0 for v in ( "LOCAL_RANK", "MPI_LOCALRANKID", "SLURM_LOCALID", "OMPI_COMM_WORLD_LOCAL_RANK", ): if v in os.environ: local_rank = int(os.environ[v]) break global_rank = 0 for v in ("RANK", "PMI_RANK", "SLURM_PROCID", "OMPI_COMM_WORLD_RANK"): if v in os.environ: global_rank = int(os.environ[v]) break world_size = 1 for v in ("WORLD_SIZE", "PMI_SIZE", "SLURM_NTASKS", "OMPI_COMM_WORLD_SIZE"): if v in os.environ: world_size = int(os.environ[v]) break return local_rank, global_rank, world_size def init_distributed_device(args): # Distributed training = training on more than one GPU. # Works in both single and multi-node scenarios. args.distributed = False args.world_size = 1 args.rank = 0 # global rank args.local_rank = 0 if args.horovod: assert hvd is not None, "Horovod is not installed" hvd.init() args.local_rank = int(hvd.local_rank()) args.rank = hvd.rank() args.world_size = hvd.size() args.distributed = True os.environ["LOCAL_RANK"] = str(args.local_rank) os.environ["RANK"] = str(args.rank) os.environ["WORLD_SIZE"] = str(args.world_size) elif is_using_distributed(): if "SLURM_PROCID" in os.environ: # DDP via SLURM args.local_rank, args.rank, args.world_size = world_info_from_env() # SLURM var -> torch.distributed vars in case needed os.environ["LOCAL_RANK"] = str(args.local_rank) os.environ["RANK"] = str(args.rank) os.environ["WORLD_SIZE"] = str(args.world_size) torch.distributed.init_process_group( backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank, ) else: # DDP via torchrun, torch.distributed.launch args.local_rank, _, _ = world_info_from_env() torch.distributed.init_process_group( backend=args.dist_backend, init_method=args.dist_url ) args.world_size = torch.distributed.get_world_size() args.rank = torch.distributed.get_rank() args.distributed = True else: # needed to run on single gpu torch.distributed.init_process_group( backend=args.dist_backend, init_method=args.dist_url, world_size=1, rank=0, ) if torch.cuda.is_available(): if args.distributed and not args.no_set_device_rank: device = "cuda:%d" % args.local_rank else: device = "cuda:0" torch.cuda.set_device(device) else: device = "cpu" args.device = device device = torch.device(device) return device
null
20,220
import time from contextlib import suppress import torch from tqdm import tqdm from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import ( FullStateDictConfig, StateDictType, ) from torch.distributed.fsdp.api import FullOptimStateDictConfig import os import wandb from einops import rearrange def get_mp_policy_dtype(precision: str): if "bfloat16" in precision or "bf16" in precision: return torch.bfloat16 elif precision == "fp16": return torch.float16 else: return torch.float32
null
20,221
import time from contextlib import suppress import torch from tqdm import tqdm from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import ( FullStateDictConfig, StateDictType, ) from torch.distributed.fsdp.api import FullOptimStateDictConfig import os import wandb from einops import rearrange def get_cast_dtype(precision: str): cast_dtype = None if precision == "bf16": cast_dtype = torch.bfloat16 elif precision == "fp16": cast_dtype = torch.float16 return cast_dtype def get_autocast(precision, cache_enabled=True): if precision == "amp": return torch.cuda.amp.autocast(cache_enabled=cache_enabled) elif precision == "amp_bfloat16" or precision == "amp_bf16": # amp_bfloat16 is more stable than amp float16 for clip training return lambda: torch.cuda.amp.autocast( dtype=torch.bfloat16, cache_enabled=cache_enabled ) else: return suppress class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def train_one_epoch( args, model, epoch, laion_loader, mmc4_loader, tokenizer, optimizer, lr_scheduler, device_id, wandb, ): # setup loaders num_batches_per_epoch_laion = laion_loader.num_batches num_batches_per_epoch_mmc4 = mmc4_loader.num_batches assert ( num_batches_per_epoch_laion == num_batches_per_epoch_mmc4 ), "Number of batches in laion and mmc4 datasets must be the same" num_batches_per_epoch = num_batches_per_epoch_mmc4 total_training_steps = num_batches_per_epoch * args.num_epochs autocast = get_autocast( args.precision, cache_enabled=(not args.fsdp) ) # if fsdp, disable cache to save memory cast_dtype = get_cast_dtype(args.precision) # setup model media_token_id = tokenizer("<image>", add_special_tokens=False)["input_ids"][-1] endofchunk_token_id = tokenizer("<|endofchunk|>", add_special_tokens=False)[ "input_ids" ][-1] model.train() # setup logging step_time_m = AverageMeter() data_time_m = AverageMeter() end = time.time() # loop through dataloader for num_steps, (batch_laion, batch_mmc4) in tqdm( enumerate(zip(laion_loader, mmc4_loader)), disable=args.rank != 0, total=total_training_steps, initial=(epoch * num_batches_per_epoch), ): data_time_m.update(time.time() - end) global_step = num_steps + epoch * num_batches_per_epoch #### LAION FORWARD PASS #### images = batch_laion[0].to(device_id, dtype=cast_dtype, non_blocking=True) images = rearrange(images, "(b t f) c h w -> b t f c h w", t=1, f=1) input_ids = batch_laion[1][0].to(device_id, dtype=cast_dtype, non_blocking=True) attention_mask = batch_laion[1][1].to( device_id, dtype=cast_dtype, non_blocking=True ) # set up labels; language model is expected to handle shifting labels = input_ids.clone() labels[labels == tokenizer.pad_token_id] = -100 labels[labels == media_token_id] = -100 labels = labels.to(device_id) # gradient accumulation w/ fsdp cpu offloading requires a no_sync context manager with autocast(): loss_laion = model( vision_x=images, lang_x=input_ids, attention_mask=attention_mask, labels=labels, )[0] divided_loss_laion = loss_laion / args.gradient_accumulation_steps (divided_loss_laion * args.loss_multiplier_laion).backward() #### MMC4 FORWARD PASS #### images = batch_mmc4[0].to(device_id, dtype=cast_dtype, non_blocking=True) images = rearrange(images, "b (t f) c h w -> b t f c h w", f=1) input_ids = torch.stack([x[0] for x in batch_mmc4[1]]).squeeze(1) attention_mask = torch.stack([x[1] for x in batch_mmc4[1]]).squeeze(1) # set up labels; language model is expected to handle shifting labels = input_ids.clone() labels[labels == tokenizer.pad_token_id] = -100 for i in range(labels.shape[0]): # remove loss for any token before the first <image> token label_idx = 0 while ( label_idx < labels.shape[1] and labels[i][label_idx] != media_token_id ): labels[i][label_idx] = -100 label_idx += 1 # get index of all endofchunk tokens in the sequence endofchunk_idxs = torch.where(labels[i] == endofchunk_token_id)[0] for endofchunk_idx in endofchunk_idxs: token_idx = endofchunk_idx + 1 while ( token_idx < labels.shape[1] and labels[i][token_idx] != media_token_id ): labels[i][token_idx] = -100 token_idx += 1 labels[labels == media_token_id] = -100 labels = labels.to(device_id) # gradient accumulation w/ fsdp cpu offloading requires a no_sync context manager with autocast(): loss_mmc4 = model( vision_x=images, lang_x=input_ids.to(device_id), attention_mask=attention_mask.to(device_id), labels=labels, )[0] # if loss is nan, skip this batch # this hack of skipping the batch is not FSDP-compatible if torch.isnan(loss_mmc4): print("loss is nan, skipping this batch") print("input_ids: ", tokenizer.batch_decode(input_ids)) print("labels: ", labels) print("images: ", images) optimizer.zero_grad(set_to_none=True) continue divided_loss_mmc4 = loss_mmc4 / args.gradient_accumulation_steps (divided_loss_mmc4 * args.loss_multiplier_mmc4).backward() if (not args.freeze_lm_embeddings) and ( not args.fsdp or args.fsdp_use_orig_params ): # Mask gradients for input embeddings s.t. we only update the added tokens <image> and <|endofchunk|> if args.fsdp: embed_grad = model.lang_encoder.get_input_embeddings().weight.grad else: embed_grad = ( model.module.lang_encoder.get_input_embeddings().weight.grad ) zero_mask = torch.zeros_like(embed_grad) zero_mask[media_token_id] = torch.ones_like(zero_mask[media_token_id]) zero_mask[endofchunk_token_id] = torch.ones_like( zero_mask[endofchunk_token_id] ) if args.fsdp: model.lang_encoder.get_input_embeddings().weight.grad = ( embed_grad * zero_mask ) else: model.module.lang_encoder.get_input_embeddings().weight.grad = ( embed_grad * zero_mask ) # clip gradient norm if args.fsdp: """ The way we clip gradients with FSDP is different than the non-FSDP case, because during FSDP, gradient norms are computed over certain submodules, rather than the entire model. At least for OPT-125M, this didn't seem to make a difference in performance. """ model.clip_grad_norm_(1.0) else: torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # step optimizer and log if (((num_steps + 1) % args.gradient_accumulation_steps) == 0) or ( num_steps == num_batches_per_epoch - 1 ): optimizer.step() lr_scheduler.step() optimizer.zero_grad(set_to_none=True) # step time and reset end outside of rank 0 step_time_m.update(time.time() - end) end = time.time() # rank 0 logging if args.rank == 0 and args.report_to_wandb: laion_samples_per_second = ( args.gradient_accumulation_steps * args.batch_size_laion * args.world_size / step_time_m.val ) laion_samples_per_second_per_gpu = ( args.gradient_accumulation_steps * args.batch_size_laion / step_time_m.val ) c4_samples_per_second = ( args.gradient_accumulation_steps * args.batch_size_mmc4 * args.world_size / step_time_m.val ) c4_samples_per_second_per_gpu = ( args.gradient_accumulation_steps * args.batch_size_mmc4 / step_time_m.val ) wandb.log( { "data_time": data_time_m.avg, "step_time": step_time_m.avg, "laion_samples_per_second": laion_samples_per_second, "laion_samples_per_second_per_gpu": laion_samples_per_second_per_gpu, "c4_samples_per_second": c4_samples_per_second, "c4_samples_per_second_per_gpu": c4_samples_per_second_per_gpu, "lr": optimizer.param_groups[0]["lr"], }, commit=False, ) step_time_m.reset() data_time_m.reset() wandb.log( { "loss_laion": loss_laion.item(), "global_step": global_step, }, commit=False, ) wandb.log( {"loss_mmc4": loss_mmc4.item(), "global_step": global_step}, commit=True, ) # Log loss to console if ((num_steps + 1) % args.logging_steps == 0) and args.rank == 0: print( f"Step {num_steps+1}/{num_batches_per_epoch} of epoch {epoch+1}/{args.num_epochs} complete. Loss LAION: {loss_laion.item():.3f} // Loss MMC4: {loss_mmc4.item():.3f}" )
null
20,222
import time from contextlib import suppress import torch from tqdm import tqdm from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import ( FullStateDictConfig, StateDictType, ) from torch.distributed.fsdp.api import FullOptimStateDictConfig import os import wandb from einops import rearrange def filter_state_dict_to_trainable(model, state_dict): """ Remove non-trainable parameters from model state dict. Exception: Embeddings will not be removed, even if frozen. This is because we need the new <image> <|endofchunk|> tokens to be consistent across initializations. """ for ( name, p, ) in model.named_parameters(): # won't work for fsdp + use_orig_params=False if "fsdp" in name: continue if "embed" in name or isinstance(p, torch.nn.Embedding): continue if not p.requires_grad: name = name.replace("._checkpoint_wrapped_module", "") if name in state_dict: del state_dict[name] else: print(f"WARNING: filtering but {name} not in state_dict") # also remove the keys in state_dict generated from # lang_encoder.old_decoder_blocks and lang_encoder.gated_cross_attn_layers # because these are already saved in lang_encoder.model... to_delete = [ n for n in state_dict.keys() if ("lang_encoder.old_decoder_blocks" in n) or ("lang_encoder.gated_cross_attn_layers" in n) or ("vision_encoder" in n) ] for name in to_delete: del state_dict[name] return state_dict The provided code snippet includes necessary dependencies for implementing the `save_checkpoint` function. Write a Python function `def save_checkpoint(model, optimizer, lr_scheduler, epoch, args)` to solve the following problem: Save training checkpoint with model, optimizer, and lr_scheduler state. Here is the function: def save_checkpoint(model, optimizer, lr_scheduler, epoch, args): """ Save training checkpoint with model, optimizer, and lr_scheduler state. """ if args.fsdp: FSDP.set_state_dict_type( model, StateDictType.FULL_STATE_DICT, FullStateDictConfig(rank0_only=True, offload_to_cpu=True), FullOptimStateDictConfig(rank0_only=True), ) model_state = model.state_dict() optim_state = FSDP.optim_state_dict(model, optimizer, group=args.my_group) else: model_state = model.state_dict() optim_state = optimizer.state_dict() if args.rank == 0: if not (args.fsdp and not args.fsdp_use_orig_params): model_state = filter_state_dict_to_trainable(model, model_state) if not os.path.exists(args.run_name): os.makedirs(args.run_name) checkpoint_dict = { "epoch": epoch, "model_state_dict": model_state, "optimizer_state_dict": optim_state, "lr_scheduler_state_dict": lr_scheduler.state_dict(), } print(f"Saving checkpoint to {args.run_name}/checkpoint_{epoch}.pt") torch.save(checkpoint_dict, f"{args.run_name}/checkpoint_{epoch}.pt") if args.report_to_wandb and args.save_checkpoints_to_wandb: wandb.save(f"{args.run_name}/checkpoint_{epoch}.pt") if args.delete_previous_checkpoint: if epoch > 0: os.remove(f"{args.run_name}/checkpoint_{epoch-1}.pt")
Save training checkpoint with model, optimizer, and lr_scheduler state.
20,223
import numpy as np import torch import random import torch.nn as nn from contextlib import suppress The provided code snippet includes necessary dependencies for implementing the `get_indices_of_unique` function. Write a Python function `def get_indices_of_unique(x)` to solve the following problem: Return the indices of x that correspond to unique elements. If value v is unique and two indices in x have value v, the first index is returned. Here is the function: def get_indices_of_unique(x): """ Return the indices of x that correspond to unique elements. If value v is unique and two indices in x have value v, the first index is returned. """ unique_elements = torch.unique(x) first_indices = [] for v in unique_elements: indices = torch.where(x == v)[0] first_indices.append(indices[0]) # Take the first index for each unique element return torch.tensor(first_indices)
Return the indices of x that correspond to unique elements. If value v is unique and two indices in x have value v, the first index is returned.
20,224
import numpy as np import torch import random import torch.nn as nn from contextlib import suppress The provided code snippet includes necessary dependencies for implementing the `unwrap_model` function. Write a Python function `def unwrap_model(model)` to solve the following problem: Unwrap a model from a DataParallel or DistributedDataParallel wrapper. Here is the function: def unwrap_model(model): """ Unwrap a model from a DataParallel or DistributedDataParallel wrapper. """ if isinstance(model, (nn.DataParallel, nn.parallel.DistributedDataParallel)): return model.module else: return model
Unwrap a model from a DataParallel or DistributedDataParallel wrapper.
20,225
import numpy as np import torch import random import torch.nn as nn from contextlib import suppress def get_cast_dtype(precision: str): cast_dtype = None if precision == "bf16": cast_dtype = torch.bfloat16 elif precision == "fp16": cast_dtype = torch.float16 return cast_dtype
null
20,226
import numpy as np import torch import random import torch.nn as nn from contextlib import suppress def get_autocast(precision): if precision == "amp": return torch.cuda.amp.autocast elif precision == "amp_bfloat16" or precision == "amp_bf16": # amp_bfloat16 is more stable than amp float16 for clip training return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16) else: return suppress
null
20,227
import argparse import importlib import json import os import uuid import random from collections import defaultdict import numpy as np import torch from sklearn.metrics import roc_auc_score import utils import math from coco_metric import compute_cider, postprocess_captioning_generation from eval_datasets import ( CaptionDataset, VQADataset, ImageNetDataset, HatefulMemesDataset, ) from rices import RICES from tqdm import tqdm from classification_utils import ( IMAGENET_CLASSNAMES, HM_CLASSNAMES, ) from eval_model import BaseEvalModel from ok_vqa_utils import postprocess_ok_vqa_generation from open_flamingo.src.flamingo import Flamingo from vqa_metric import compute_vqa_accuracy, postprocess_vqa_generation from open_flamingo.train.distributed import init_distributed_device, world_info_from_env def compute_cider( result_path, annotations_path, ): # create coco object and coco_result object coco = COCO(annotations_path) coco_result = coco.loadRes(result_path) # create coco_eval object by taking coco and coco_result coco_eval = COCOEvalCap(coco, coco_result) coco_eval.params["image_id"] = coco_result.getImgIds() coco_eval.evaluate() return coco_eval.eval def postprocess_captioning_generation(predictions): return predictions.split("Output", 1)[0] class CaptionDataset(Dataset): def __init__( self, image_train_dir_path, annotations_path, is_train, dataset_name, image_val_dir_path=None, ): self.image_train_dir_path = image_train_dir_path self.image_val_dir_path = image_val_dir_path self.annotations = [] self.is_train = is_train self.dataset_name = dataset_name full_annotations = json.load(open(annotations_path))["images"] for i in range(len(full_annotations)): if self.is_train and full_annotations[i]["split"] != "train": continue elif not self.is_train and full_annotations[i]["split"] != "test": continue self.annotations.append(full_annotations[i]) def __len__(self): return len(self.annotations) def __getitem__(self, idx): if self.dataset_name == "coco": image = Image.open( os.path.join( self.image_train_dir_path, self.annotations[idx]["filename"] ) if self.annotations[idx]["filepath"] == "train2014" else os.path.join( self.image_val_dir_path, self.annotations[idx]["filename"] ) ) elif self.dataset_name == "flickr": image = Image.open( os.path.join( self.image_train_dir_path, self.annotations[idx]["filename"] ) ) image.load() caption = self.annotations[idx]["sentences"][0]["raw"] return { "image": image, "caption": caption, "image_id": self.annotations[idx]["cocoid"] if self.dataset_name == "coco" else self.annotations[idx]["filename"].split(".")[0], } class RICES: def __init__( self, dataset, device, batch_size, vision_encoder_path="ViT-B-32", vision_encoder_pretrained="openai", cached_features=None, ): self.dataset = dataset self.device = device self.batch_size = batch_size # Load the model and processor vision_encoder, _, image_processor = open_clip.create_model_and_transforms( vision_encoder_path, pretrained=vision_encoder_pretrained, ) self.model = vision_encoder.to(self.device) self.image_processor = image_processor # Precompute features if cached_features is None: self.features = self._precompute_features() else: self.features = cached_features def _precompute_features(self): features = [] # Switch to evaluation mode self.model.eval() # Set up loader loader = torch.utils.data.DataLoader( self.dataset, batch_size=self.batch_size, collate_fn=custom_collate_fn, ) with torch.no_grad(): for batch in tqdm( loader, desc="Precomputing features for RICES", ): batch = batch["image"] inputs = torch.stack( [self.image_processor(image) for image in batch] ).to(self.device) image_features = self.model.encode_image(inputs) image_features /= image_features.norm(dim=-1, keepdim=True) features.append(image_features.detach()) features = torch.cat(features) return features def find(self, batch, num_examples): """ Get the top num_examples most similar examples to the images. """ # Switch to evaluation mode self.model.eval() with torch.no_grad(): inputs = torch.stack([self.image_processor(image) for image in batch]).to( self.device ) # Get the feature of the input image query_feature = self.model.encode_image(inputs) query_feature /= query_feature.norm(dim=-1, keepdim=True) query_feature = query_feature.detach().cpu() if query_feature.ndim == 1: query_feature = query_feature.unsqueeze(0) # Compute the similarity of the input image to the precomputed features similarity = (query_feature @ self.features.T).squeeze() if similarity.ndim == 1: similarity = similarity.unsqueeze(0) # Get the indices of the 'num_examples' most similar images indices = similarity.argsort(dim=-1, descending=True)[:, :num_examples] # Return with the most similar images last return [[self.dataset[i] for i in reversed(row)] for row in indices] class BaseEvalModel(abc.ABC): """Base class encapsulating functionality needed to evaluate a model.""" def __init__(self, args: List[str]): """Initialize model. Args: args: arguments to model. These should be parsed, or if the model has no applicable arguments, an error should be thrown if `args` is non-empty. """ def init_distributed(self): """Wrap model as DDP.""" self.model = DDP(self.model, device_ids=[self.device]) def set_device(self, device): """Set device for model.""" self.device = device self.model = self.model.to(device) def get_outputs( self, batch_text: List[str], batch_images: List[List[Image.Image]], min_generation_length: int, max_generation_length: int, num_beams: int, length_penalty: float, ) -> List[str]: """Get outputs for a batch of images and text. Args: batch_text: list of text strings, with the text "<image>" in place of any images to be included. batch_images: images to provide to model. Should be a list of lists, where each list contains the images for a single example. max_generation_length: maximum length of the generated caption. Defaults to 10. num_beams: number of beams to use for beam search. Defaults to 3. length_penalty: length penalty for beam search. Defaults to -2.0. Returns: List of decoded output strings. """ def vqa_prompt(self, question, answer=None) -> str: """Get the prompt to use for VQA evaluation. If the answer is not provided, it should be left blank to be generated by the model. Returns: The prompt to use for VQA. """ def caption_prompt(self, caption=None) -> str: """Get the prompt to use for caption evaluation. If the caption is not provided, it should be left blank to be generated by the model. Returns: The prompt to use for captioning. """ def get_rank_classifications( self, batch_text: List[str], batch_images: List[List[Image.Image]], all_class_names: List[str], use_cache: bool, normalize_length: bool, ): """ Returns a (B, |all_class_names|) tensor containing the logprobs for each class name. Args: batch_text: list of text strings, with the text "<image>" in place of any images to be included. batch_images: images to provide to model. Should be a list of lists, where each list contains the images for a single example. all_class_names: list of all class names. use_cache: whether to cache the context to speed up evaluations. normalize_length: whether to normalize logprobs by the length of the class name Returns: (B, |all_class_names|) tensor containing the logprobs for each class name. """ The provided code snippet includes necessary dependencies for implementing the `evaluate_captioning` function. Write a Python function `def evaluate_captioning( args: argparse.Namespace, eval_model: BaseEvalModel, seed: int = 42, min_generation_length: int = 0, max_generation_length: int = 20, num_beams: int = 3, length_penalty: float = 0.0, num_shots: int = 8, dataset_name: str = "coco", cached_features=None, )` to solve the following problem: Evaluate a model on COCO dataset. Args: args (argparse.Namespace): arguments eval_model (BaseEvalModel): model to evaluate seed (int, optional): seed for random number generator. Defaults to 42. max_generation_length (int, optional): maximum length of the generated caption. Defaults to 20. num_beams (int, optional): number of beams to use for beam search. Defaults to 3. length_penalty (float, optional): length penalty for beam search. Defaults to -2.0. num_shots (int, optional): number of in-context samples to use. Defaults to 8. dataset_name (str, optional): dataset to evaluate on. Can be "coco" or "flickr". Defaults to "coco". cached_features (tensor, optional): cached demonstration features for RICES. Defaults to None. Returns: float: CIDEr score Here is the function: def evaluate_captioning( args: argparse.Namespace, eval_model: BaseEvalModel, seed: int = 42, min_generation_length: int = 0, max_generation_length: int = 20, num_beams: int = 3, length_penalty: float = 0.0, num_shots: int = 8, dataset_name: str = "coco", cached_features=None, ): """Evaluate a model on COCO dataset. Args: args (argparse.Namespace): arguments eval_model (BaseEvalModel): model to evaluate seed (int, optional): seed for random number generator. Defaults to 42. max_generation_length (int, optional): maximum length of the generated caption. Defaults to 20. num_beams (int, optional): number of beams to use for beam search. Defaults to 3. length_penalty (float, optional): length penalty for beam search. Defaults to -2.0. num_shots (int, optional): number of in-context samples to use. Defaults to 8. dataset_name (str, optional): dataset to evaluate on. Can be "coco" or "flickr". Defaults to "coco". cached_features (tensor, optional): cached demonstration features for RICES. Defaults to None. Returns: float: CIDEr score """ if dataset_name == "coco": image_train_dir_path = args.coco_train_image_dir_path image_val_dir_path = args.coco_val_image_dir_path annotations_path = args.coco_karpathy_json_path elif dataset_name == "flickr": image_train_dir_path = ( args.flickr_image_dir_path ) # Note: calling this "train" for consistency with COCO but Flickr only has one split for images image_val_dir_path = None annotations_path = args.flickr_karpathy_json_path else: raise ValueError(f"Unsupported dataset: {dataset_name}") train_dataset = CaptionDataset( image_train_dir_path=image_train_dir_path, image_val_dir_path=image_val_dir_path, annotations_path=annotations_path, is_train=True, dataset_name=dataset_name if dataset_name != "nocaps" else "coco", ) test_dataset = CaptionDataset( image_train_dir_path=image_train_dir_path, image_val_dir_path=image_val_dir_path, annotations_path=annotations_path, is_train=False, dataset_name=dataset_name, ) effective_num_shots = utils.compute_effective_num_shots(num_shots, args.model) np.random.seed(seed) test_dataloader = utils.prepare_eval_samples( test_dataset, args.num_samples if args.num_samples > 0 else len(test_dataset), args.batch_size, ) if args.rices: rices_dataset = RICES( train_dataset, eval_model.device, args.batch_size, cached_features=cached_features, vision_encoder_path=args.rices_vision_encoder_path, vision_encoder_pretrained=args.rices_vision_encoder_pretrained, ) else: # subset of the training set to sample context images from query_set = utils.get_query_set(train_dataset, args.query_set_size) utils.random_seed(seed, args.rank) predictions = defaultdict() for batch in tqdm( test_dataloader, desc=f"Running inference {dataset_name.upper()}", disable=args.rank != 0, ): if args.rices: batch_demo_samples = rices_dataset.find(batch["image"], effective_num_shots) else: batch_demo_samples = utils.sample_batch_demos_from_query_set( query_set, effective_num_shots, len(batch["image"]) ) batch_images, batch_text = [], [] for i in range(len(batch["image"])): if num_shots > 0: context_images = [x["image"] for x in batch_demo_samples[i]] else: context_images = [] batch_images.append(context_images + [batch["image"][i]]) context_text = "".join( [ eval_model.get_caption_prompt(caption=x["caption"].strip()) + "\n" for x in batch_demo_samples[i] ] ) # Keep the text but remove the image tags for the zero-shot case if num_shots == 0: context_text = context_text.replace("<image>", "") batch_text.append(context_text + eval_model.get_caption_prompt()) outputs = eval_model.get_outputs( batch_images=batch_images, batch_text=batch_text, min_generation_length=min_generation_length, max_generation_length=max_generation_length, num_beams=num_beams, length_penalty=length_penalty, ) new_predictions = [ postprocess_captioning_generation(out).replace('"', "") for out in outputs ] for i, sample_id in enumerate(batch["image_id"]): predictions[sample_id] = { "caption": new_predictions[i], } # all gather all_predictions = [None for _ in range(args.world_size)] torch.distributed.all_gather_object(all_predictions, predictions) # list of dicts if args.rank != 0: return None all_predictions = { k: v for d in all_predictions for k, v in d.items() } # merge dicts # save the predictions to a temporary file results_path = f"{dataset_name}results_{uuid.uuid4()}.json" with open(results_path, "w") as f: f.write( json.dumps( [ {"image_id": k, "caption": all_predictions[k]["caption"]} for k in all_predictions ], indent=4, ) ) metrics = compute_cider( result_path=results_path, annotations_path=args.coco_annotations_json_path if dataset_name == "coco" else args.flickr_annotations_json_path, ) # delete the temporary file os.remove(results_path) return metrics["CIDEr"] * 100.0
Evaluate a model on COCO dataset. Args: args (argparse.Namespace): arguments eval_model (BaseEvalModel): model to evaluate seed (int, optional): seed for random number generator. Defaults to 42. max_generation_length (int, optional): maximum length of the generated caption. Defaults to 20. num_beams (int, optional): number of beams to use for beam search. Defaults to 3. length_penalty (float, optional): length penalty for beam search. Defaults to -2.0. num_shots (int, optional): number of in-context samples to use. Defaults to 8. dataset_name (str, optional): dataset to evaluate on. Can be "coco" or "flickr". Defaults to "coco". cached_features (tensor, optional): cached demonstration features for RICES. Defaults to None. Returns: float: CIDEr score
20,228
import argparse import importlib import json import os import uuid import random from collections import defaultdict import numpy as np import torch from sklearn.metrics import roc_auc_score import utils import math from coco_metric import compute_cider, postprocess_captioning_generation from eval_datasets import ( CaptionDataset, VQADataset, ImageNetDataset, HatefulMemesDataset, ) from rices import RICES from tqdm import tqdm from classification_utils import ( IMAGENET_CLASSNAMES, HM_CLASSNAMES, ) from eval_model import BaseEvalModel from ok_vqa_utils import postprocess_ok_vqa_generation from open_flamingo.src.flamingo import Flamingo from vqa_metric import compute_vqa_accuracy, postprocess_vqa_generation from open_flamingo.train.distributed import init_distributed_device, world_info_from_env class VQADataset(Dataset): def __init__( self, image_dir_path, question_path, annotations_path, is_train, dataset_name ): self.questions = json.load(open(question_path, "r"))["questions"] if annotations_path is not None: self.answers = json.load(open(annotations_path, "r"))["annotations"] else: self.answers = None self.image_dir_path = image_dir_path self.is_train = is_train self.dataset_name = dataset_name if self.dataset_name in {"vqav2", "ok_vqa"}: self.img_coco_split = self.image_dir_path.strip("/").split("/")[-1] assert self.img_coco_split in {"train2014", "val2014", "test2015"} def __len__(self): return len(self.questions) def get_img_path(self, question): if self.dataset_name in {"vqav2", "ok_vqa"}: return os.path.join( self.image_dir_path, f"COCO_{self.img_coco_split}_{question['image_id']:012d}.jpg" if self.is_train else f"COCO_{self.img_coco_split}_{question['image_id']:012d}.jpg", ) elif self.dataset_name == "vizwiz": return os.path.join(self.image_dir_path, question["image_id"]) elif self.dataset_name == "textvqa": return os.path.join(self.image_dir_path, f"{question['image_id']}.jpg") else: raise Exception(f"Unknown VQA dataset {self.dataset_name}") def __getitem__(self, idx): question = self.questions[idx] img_path = self.get_img_path(question) image = Image.open(img_path) image.load() results = { "image": image, "question": question["question"], "question_id": question["question_id"], } if self.answers is not None: answers = self.answers[idx] results["answers"] = [a["answer"] for a in answers["answers"]] return results class RICES: def __init__( self, dataset, device, batch_size, vision_encoder_path="ViT-B-32", vision_encoder_pretrained="openai", cached_features=None, ): self.dataset = dataset self.device = device self.batch_size = batch_size # Load the model and processor vision_encoder, _, image_processor = open_clip.create_model_and_transforms( vision_encoder_path, pretrained=vision_encoder_pretrained, ) self.model = vision_encoder.to(self.device) self.image_processor = image_processor # Precompute features if cached_features is None: self.features = self._precompute_features() else: self.features = cached_features def _precompute_features(self): features = [] # Switch to evaluation mode self.model.eval() # Set up loader loader = torch.utils.data.DataLoader( self.dataset, batch_size=self.batch_size, collate_fn=custom_collate_fn, ) with torch.no_grad(): for batch in tqdm( loader, desc="Precomputing features for RICES", ): batch = batch["image"] inputs = torch.stack( [self.image_processor(image) for image in batch] ).to(self.device) image_features = self.model.encode_image(inputs) image_features /= image_features.norm(dim=-1, keepdim=True) features.append(image_features.detach()) features = torch.cat(features) return features def find(self, batch, num_examples): """ Get the top num_examples most similar examples to the images. """ # Switch to evaluation mode self.model.eval() with torch.no_grad(): inputs = torch.stack([self.image_processor(image) for image in batch]).to( self.device ) # Get the feature of the input image query_feature = self.model.encode_image(inputs) query_feature /= query_feature.norm(dim=-1, keepdim=True) query_feature = query_feature.detach().cpu() if query_feature.ndim == 1: query_feature = query_feature.unsqueeze(0) # Compute the similarity of the input image to the precomputed features similarity = (query_feature @ self.features.T).squeeze() if similarity.ndim == 1: similarity = similarity.unsqueeze(0) # Get the indices of the 'num_examples' most similar images indices = similarity.argsort(dim=-1, descending=True)[:, :num_examples] # Return with the most similar images last return [[self.dataset[i] for i in reversed(row)] for row in indices] class BaseEvalModel(abc.ABC): """Base class encapsulating functionality needed to evaluate a model.""" def __init__(self, args: List[str]): """Initialize model. Args: args: arguments to model. These should be parsed, or if the model has no applicable arguments, an error should be thrown if `args` is non-empty. """ def init_distributed(self): """Wrap model as DDP.""" self.model = DDP(self.model, device_ids=[self.device]) def set_device(self, device): """Set device for model.""" self.device = device self.model = self.model.to(device) def get_outputs( self, batch_text: List[str], batch_images: List[List[Image.Image]], min_generation_length: int, max_generation_length: int, num_beams: int, length_penalty: float, ) -> List[str]: """Get outputs for a batch of images and text. Args: batch_text: list of text strings, with the text "<image>" in place of any images to be included. batch_images: images to provide to model. Should be a list of lists, where each list contains the images for a single example. max_generation_length: maximum length of the generated caption. Defaults to 10. num_beams: number of beams to use for beam search. Defaults to 3. length_penalty: length penalty for beam search. Defaults to -2.0. Returns: List of decoded output strings. """ def vqa_prompt(self, question, answer=None) -> str: """Get the prompt to use for VQA evaluation. If the answer is not provided, it should be left blank to be generated by the model. Returns: The prompt to use for VQA. """ def caption_prompt(self, caption=None) -> str: """Get the prompt to use for caption evaluation. If the caption is not provided, it should be left blank to be generated by the model. Returns: The prompt to use for captioning. """ def get_rank_classifications( self, batch_text: List[str], batch_images: List[List[Image.Image]], all_class_names: List[str], use_cache: bool, normalize_length: bool, ): """ Returns a (B, |all_class_names|) tensor containing the logprobs for each class name. Args: batch_text: list of text strings, with the text "<image>" in place of any images to be included. batch_images: images to provide to model. Should be a list of lists, where each list contains the images for a single example. all_class_names: list of all class names. use_cache: whether to cache the context to speed up evaluations. normalize_length: whether to normalize logprobs by the length of the class name Returns: (B, |all_class_names|) tensor containing the logprobs for each class name. """ def postprocess_ok_vqa_generation(predictions) -> str: prediction = re.split("Question|Answer|Short", predictions, 1)[0] prediction = re.split(", ", prediction, 1)[0] prediction_stem = stemmer.stem(prediction) return prediction_stem def compute_vqa_accuracy(result_json_path, question_json_path, annotation_json_path): """Compute the VQA accuracy metric. Args: result_json_path (str): Path to the json file with model outputs question_json_path (str): Path to the json file with questions annotation_json_path (str): Path to the json file with annotations Returns: float: VQA accuracy """ # create vqa object and vqaRes object vqa = VQA(annotation_json_path, question_json_path) vqaRes = vqa.loadRes(result_json_path, question_json_path) # create vqaEval object by taking vqa and vqaRes # n is precision of accuracy (number of places after decimal), default is 2 vqaEval = VQAEval(vqa, vqaRes, n=2) # evaluate results """ If you have a list of question ids on which you would like to evaluate your results, pass it as a list to below function By default it uses all the question ids in annotation file """ vqaEval.evaluate() return vqaEval.accuracy["overall"] def postprocess_vqa_generation(predictions): answer = re.split("Question|Answer|Short", predictions, 1)[0] answer = re.split(", ", answer, 1)[0] return answer def fill_vizwiz_test_json( input_path, output_path, vqa_test_questions_json_path, ): # read the input json and build a set with all question_ids with open(input_path, "r") as f: input_json = json.load(f) # postprocess answers question_id_to_answer = {} for q in input_json: resAns = q["answer"] resAns = resAns.replace("\n", " ") resAns = resAns.replace("\t", " ") resAns = resAns.strip() resAns = postprocessor.processPunctuation(resAns) resAns = postprocessor.processDigitArticle(resAns) question_id_to_answer[q["question_id"]] = resAns # read the vqa test json to get all the qustion_ids that need to be filled with open(vqa_test_questions_json_path, "r") as f: vqa_test_json = json.load(f) vqa_test_json = vqa_test_json["questions"] # if the question_id is not in the set, add it to the copy of the input json with an empty string as the answer output_json = [] for q in vqa_test_json: output_json.append( { "image": q["image_id"], "answer": question_id_to_answer.get(q["question_id"], ""), } ) # write the json to the output path with open(output_path, "w") as f: json.dump(output_json, f) def fill_vqav2_test_json( input_path, output_path, vqa_test_questions_json_path, ): # read the input json and build a set with all question_ids with open(input_path, "r") as f: input_json = json.load(f) question_ids = set() for q in input_json: question_ids.add(q["question_id"]) # make a copy of the input json output_json = [] for q in input_json: resAns = q["answer"] resAns = resAns.replace("\n", " ") resAns = resAns.replace("\t", " ") resAns = resAns.strip() resAns = postprocessor.processPunctuation(resAns) resAns = postprocessor.processDigitArticle(resAns) q["answer"] = resAns output_json.append(q) # read the vqa test json to get all the qustion_ids that need to be filled with open(vqa_test_questions_json_path, "r") as f: vqa_test_json = json.load(f) vqa_test_json = vqa_test_json["questions"] # if the question_id is not in the set, add it to the copy of the input json with an empty string as the answer for q in vqa_test_json: if q["question_id"] not in question_ids: output_json.append( { "question_id": q["question_id"], "answer": "", } ) # write the json to the output path with open(output_path, "w") as f: json.dump(output_json, f) The provided code snippet includes necessary dependencies for implementing the `evaluate_vqa` function. Write a Python function `def evaluate_vqa( args: argparse.Namespace, eval_model: BaseEvalModel, seed: int = 42, min_generation_length: int = 0, max_generation_length: int = 5, num_beams: int = 3, length_penalty: float = 0.0, num_shots: int = 8, dataset_name: str = "vqav2", cached_features=None, )` to solve the following problem: Evaluate a model on VQA datasets. Currently supports VQA v2.0, OK-VQA, VizWiz and TextVQA. Args: args (argparse.Namespace): arguments eval_model (BaseEvalModel): model to evaluate seed (int, optional): random seed. Defaults to 42. max_generation_length (int, optional): max generation length. Defaults to 5. num_beams (int, optional): number of beams to use for beam search. Defaults to 3. length_penalty (float, optional): length penalty for beam search. Defaults to -2.0. num_shots (int, optional): number of shots to use. Defaults to 8. dataset_name (string): type of vqa dataset: currently supports vqav2, ok_vqa. Defaults to vqav2. cached_features (tensor, optional): cached demonstration features for RICES. Defaults to None. Returns: float: accuracy score Here is the function: def evaluate_vqa( args: argparse.Namespace, eval_model: BaseEvalModel, seed: int = 42, min_generation_length: int = 0, max_generation_length: int = 5, num_beams: int = 3, length_penalty: float = 0.0, num_shots: int = 8, dataset_name: str = "vqav2", cached_features=None, ): """ Evaluate a model on VQA datasets. Currently supports VQA v2.0, OK-VQA, VizWiz and TextVQA. Args: args (argparse.Namespace): arguments eval_model (BaseEvalModel): model to evaluate seed (int, optional): random seed. Defaults to 42. max_generation_length (int, optional): max generation length. Defaults to 5. num_beams (int, optional): number of beams to use for beam search. Defaults to 3. length_penalty (float, optional): length penalty for beam search. Defaults to -2.0. num_shots (int, optional): number of shots to use. Defaults to 8. dataset_name (string): type of vqa dataset: currently supports vqav2, ok_vqa. Defaults to vqav2. cached_features (tensor, optional): cached demonstration features for RICES. Defaults to None. Returns: float: accuracy score """ if dataset_name == "ok_vqa": train_image_dir_path = args.ok_vqa_train_image_dir_path train_questions_json_path = args.ok_vqa_train_questions_json_path train_annotations_json_path = args.ok_vqa_train_annotations_json_path test_image_dir_path = args.ok_vqa_test_image_dir_path test_questions_json_path = args.ok_vqa_test_questions_json_path test_annotations_json_path = args.ok_vqa_test_annotations_json_path elif dataset_name == "vqav2": train_image_dir_path = args.vqav2_train_image_dir_path train_questions_json_path = args.vqav2_train_questions_json_path train_annotations_json_path = args.vqav2_train_annotations_json_path test_image_dir_path = args.vqav2_test_image_dir_path test_questions_json_path = args.vqav2_test_questions_json_path test_annotations_json_path = args.vqav2_test_annotations_json_path elif dataset_name == "vizwiz": train_image_dir_path = args.vizwiz_train_image_dir_path train_questions_json_path = args.vizwiz_train_questions_json_path train_annotations_json_path = args.vizwiz_train_annotations_json_path test_image_dir_path = args.vizwiz_test_image_dir_path test_questions_json_path = args.vizwiz_test_questions_json_path test_annotations_json_path = args.vizwiz_test_annotations_json_path elif dataset_name == "textvqa": train_image_dir_path = args.textvqa_image_dir_path train_questions_json_path = args.textvqa_train_questions_json_path train_annotations_json_path = args.textvqa_train_annotations_json_path test_image_dir_path = args.textvqa_image_dir_path test_questions_json_path = args.textvqa_test_questions_json_path test_annotations_json_path = args.textvqa_test_annotations_json_path else: raise ValueError(f"Unsupported dataset: {dataset_name}") train_dataset = VQADataset( image_dir_path=train_image_dir_path, question_path=train_questions_json_path, annotations_path=train_annotations_json_path, is_train=True, dataset_name=dataset_name, ) test_dataset = VQADataset( image_dir_path=test_image_dir_path, question_path=test_questions_json_path, annotations_path=test_annotations_json_path, is_train=False, dataset_name=dataset_name, ) effective_num_shots = utils.compute_effective_num_shots(num_shots, args.model) np.random.seed(seed) test_dataloader = utils.prepare_eval_samples( test_dataset, args.num_samples if args.num_samples > 0 else len(test_dataset), args.batch_size, ) if args.rices: rices_dataset = RICES( train_dataset, eval_model.device, args.batch_size, cached_features=cached_features, vision_encoder_path=args.rices_vision_encoder_path, vision_encoder_pretrained=args.rices_vision_encoder_pretrained, ) else: query_set = utils.get_query_set(train_dataset, args.query_set_size) utils.random_seed(seed, args.rank) predictions = [] for batch in tqdm( test_dataloader, desc=f"Running inference {dataset_name}", disable=args.rank != 0, ): if args.rices: batch_demo_samples = rices_dataset.find(batch["image"], effective_num_shots) else: batch_demo_samples = utils.sample_batch_demos_from_query_set( query_set, effective_num_shots, len(batch["image"]) ) batch_images, batch_text = [], [] for i in range(len(batch["image"])): if num_shots > 0: context_images = [x["image"] for x in batch_demo_samples[i]] else: context_images = [] batch_images.append(context_images + [batch["image"][i]]) context_text = "".join( [ eval_model.get_vqa_prompt( question=x["question"], answer=x["answers"][0] ) + "\n" for x in batch_demo_samples[i] ] ) # Keep the text but remove the image tags for the zero-shot case if num_shots == 0: context_text = context_text.replace("<image>", "") batch_text.append( context_text + eval_model.get_vqa_prompt(question=batch["question"][i]) ) outputs = eval_model.get_outputs( batch_images=batch_images, batch_text=batch_text, min_generation_length=min_generation_length, max_generation_length=max_generation_length, num_beams=num_beams, length_penalty=length_penalty, ) process_function = ( postprocess_ok_vqa_generation if dataset_name == "ok_vqa" else postprocess_vqa_generation ) new_predictions = map(process_function, outputs) for new_prediction, sample_id in zip(new_predictions, batch["question_id"]): predictions.append({"answer": new_prediction, "question_id": sample_id}) # all gather all_predictions = [None for _ in range(args.world_size)] torch.distributed.all_gather_object(all_predictions, predictions) # list of lists if args.rank != 0: return None all_predictions = [ item for sublist in all_predictions for item in sublist ] # flatten # save the predictions to a temporary file random_uuid = str(uuid.uuid4()) with open(f"{dataset_name}results_{random_uuid}.json", "w") as f: f.write(json.dumps(all_predictions, indent=4)) if test_annotations_json_path is not None: acc = compute_vqa_accuracy( f"{dataset_name}results_{random_uuid}.json", test_questions_json_path, test_annotations_json_path, ) # delete the temporary file os.remove(f"{dataset_name}results_{random_uuid}.json") else: print("No annotations provided, skipping accuracy computation.") acc = None if dataset_name == "vqav2": from open_flamingo.scripts.fill_vqa_testdev_results import ( fill_vqav2_test_json, ) fill_fn = fill_vqav2_test_json elif dataset_name == "vizwiz": from open_flamingo.scripts.fill_vqa_testdev_results import ( fill_vizwiz_test_json, ) fill_fn = fill_vizwiz_test_json else: print( "Temporary file saved to ", f"{dataset_name}results_{random_uuid}.json" ) return fill_fn( f"{dataset_name}results_{random_uuid}.json", f"{dataset_name}-testdev_{eval_model.lm_name}_{num_shots}_{'rices' if args.rices else 'random'}_{seed}.json", args.vqav2_final_test_questions_json_path if dataset_name == "vqav2" else args.vizwiz_test_questions_json_path, ) print( "Test-dev results saved to ", f"{dataset_name}-testdev_{eval_model.lm_name}_{num_shots}_{'rices' if args.rices else 'random'}_{seed}.json", ) os.remove(f"{dataset_name}results_{random_uuid}.json") return acc
Evaluate a model on VQA datasets. Currently supports VQA v2.0, OK-VQA, VizWiz and TextVQA. Args: args (argparse.Namespace): arguments eval_model (BaseEvalModel): model to evaluate seed (int, optional): random seed. Defaults to 42. max_generation_length (int, optional): max generation length. Defaults to 5. num_beams (int, optional): number of beams to use for beam search. Defaults to 3. length_penalty (float, optional): length penalty for beam search. Defaults to -2.0. num_shots (int, optional): number of shots to use. Defaults to 8. dataset_name (string): type of vqa dataset: currently supports vqav2, ok_vqa. Defaults to vqav2. cached_features (tensor, optional): cached demonstration features for RICES. Defaults to None. Returns: float: accuracy score
20,229
import argparse import importlib import json import os import uuid import random from collections import defaultdict import numpy as np import torch from sklearn.metrics import roc_auc_score import utils import math from coco_metric import compute_cider, postprocess_captioning_generation from eval_datasets import ( CaptionDataset, VQADataset, ImageNetDataset, HatefulMemesDataset, ) from rices import RICES from tqdm import tqdm from classification_utils import ( IMAGENET_CLASSNAMES, HM_CLASSNAMES, ) from eval_model import BaseEvalModel from ok_vqa_utils import postprocess_ok_vqa_generation from open_flamingo.src.flamingo import Flamingo from vqa_metric import compute_vqa_accuracy, postprocess_vqa_generation from open_flamingo.train.distributed import init_distributed_device, world_info_from_env class ImageNetDataset(ImageFolder): """Class to represent the ImageNet1k dataset.""" def __init__(self, root, **kwargs): super().__init__(root=root, **kwargs) self.class_id_to_name = dict( zip(range(len(IMAGENET_CLASSNAMES)), IMAGENET_CLASSNAMES) ) def __getitem__(self, idx): sample, target = super().__getitem__(idx) target_label = self.class_id_to_name[target] return { "id": idx, "image": sample, "class_id": target, # numeric ID of the ImageNet class "class_name": target_label, # human-readable name of ImageNet class } class HatefulMemesDataset(Dataset): def __init__(self, image_dir_path, annotations_path): self.image_dir_path = image_dir_path with open(annotations_path, "r") as f: self.annotations = [json.loads(line) for line in f] def __len__(self): return len(self.annotations) def __getitem__(self, idx): annotation = self.annotations[idx] img_path = os.path.join(self.image_dir_path, annotation["img"].split("/")[-1]) image = Image.open(img_path) image.load() return { "id": annotation["id"], "image": image, "ocr": annotation["text"], "class_name": "yes" if annotation["label"] == 1 else "no", "class_id": annotation["label"], } class RICES: def __init__( self, dataset, device, batch_size, vision_encoder_path="ViT-B-32", vision_encoder_pretrained="openai", cached_features=None, ): self.dataset = dataset self.device = device self.batch_size = batch_size # Load the model and processor vision_encoder, _, image_processor = open_clip.create_model_and_transforms( vision_encoder_path, pretrained=vision_encoder_pretrained, ) self.model = vision_encoder.to(self.device) self.image_processor = image_processor # Precompute features if cached_features is None: self.features = self._precompute_features() else: self.features = cached_features def _precompute_features(self): features = [] # Switch to evaluation mode self.model.eval() # Set up loader loader = torch.utils.data.DataLoader( self.dataset, batch_size=self.batch_size, collate_fn=custom_collate_fn, ) with torch.no_grad(): for batch in tqdm( loader, desc="Precomputing features for RICES", ): batch = batch["image"] inputs = torch.stack( [self.image_processor(image) for image in batch] ).to(self.device) image_features = self.model.encode_image(inputs) image_features /= image_features.norm(dim=-1, keepdim=True) features.append(image_features.detach()) features = torch.cat(features) return features def find(self, batch, num_examples): """ Get the top num_examples most similar examples to the images. """ # Switch to evaluation mode self.model.eval() with torch.no_grad(): inputs = torch.stack([self.image_processor(image) for image in batch]).to( self.device ) # Get the feature of the input image query_feature = self.model.encode_image(inputs) query_feature /= query_feature.norm(dim=-1, keepdim=True) query_feature = query_feature.detach().cpu() if query_feature.ndim == 1: query_feature = query_feature.unsqueeze(0) # Compute the similarity of the input image to the precomputed features similarity = (query_feature @ self.features.T).squeeze() if similarity.ndim == 1: similarity = similarity.unsqueeze(0) # Get the indices of the 'num_examples' most similar images indices = similarity.argsort(dim=-1, descending=True)[:, :num_examples] # Return with the most similar images last return [[self.dataset[i] for i in reversed(row)] for row in indices] IMAGENET_CLASSNAMES = [ "tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", "box turtle", "banded gecko", "green iguana", "Carolina anole", "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", "American alligator", "triceratops", "worm snake", "ring-necked snake", "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", "freight car", "French horn", "frying pan", "fur coat", "garbage truck", "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper", ] HM_CLASSNAMES = [ "no", "yes", ] The provided code snippet includes necessary dependencies for implementing the `evaluate_classification` function. Write a Python function `def evaluate_classification( args: argparse.Namespace, eval_model, seed: int = 42, num_shots: int = 8, dataset_name: str = "imagenet", cached_features=None, no_kv_caching=False, use_prompt_ensembling: bool = False, )` to solve the following problem: Evaluate a model on classification dataset. Args: eval_model (BaseEvalModel): model to evaluate seed (int, optional): random seed. Defaults to 42. num_shots (int, optional): number of shots to use. Defaults to 8. no_kv_caching (bool): whether to disable key-value caching dataset_name (str, optional): dataset name. Defaults to "imagenet". cached_features (tensor, optional): cached demonstration features for RICES. Defaults to None. Returns: float: accuracy score Here is the function: def evaluate_classification( args: argparse.Namespace, eval_model, seed: int = 42, num_shots: int = 8, dataset_name: str = "imagenet", cached_features=None, no_kv_caching=False, use_prompt_ensembling: bool = False, ): """ Evaluate a model on classification dataset. Args: eval_model (BaseEvalModel): model to evaluate seed (int, optional): random seed. Defaults to 42. num_shots (int, optional): number of shots to use. Defaults to 8. no_kv_caching (bool): whether to disable key-value caching dataset_name (str, optional): dataset name. Defaults to "imagenet". cached_features (tensor, optional): cached demonstration features for RICES. Defaults to None. Returns: float: accuracy score """ if args.model != "open_flamingo": raise NotImplementedError( "evaluate_classification is currently only supported for OpenFlamingo" ) if dataset_name == "imagenet": train_dataset = ImageNetDataset(os.path.join(args.imagenet_root, "train")) test_dataset = ImageNetDataset(os.path.join(args.imagenet_root, "val")) prompt_fn = lambda x: eval_model.get_imagenet_prompt(label=x["class_name"]) all_class_names = IMAGENET_CLASSNAMES k = 5 elif dataset_name == "hateful_memes": train_dataset = HatefulMemesDataset( args.hateful_memes_image_dir_path, args.hateful_memes_train_annotations_json_path, ) test_dataset = HatefulMemesDataset( args.hateful_memes_image_dir_path, args.hateful_memes_test_annotations_json_path, ) prompt_fn = lambda x: eval_model.get_hateful_memes_prompt( text=x["ocr"], label=x["class_name"] ) all_class_names = HM_CLASSNAMES k = 1 else: raise ValueError(f"Unsupported dataset {dataset_name}") class_id_to_name = dict(zip(range(len(all_class_names)), all_class_names)) effective_num_shots = utils.compute_effective_num_shots(num_shots, args.model) np.random.seed(seed) test_dataloader = utils.prepare_eval_samples( test_dataset, args.num_samples if args.num_samples > 0 else len(test_dataset), args.batch_size, ) if args.rices: rices_dataset = RICES( train_dataset, eval_model.device, args.batch_size, cached_features=cached_features, vision_encoder_path=args.rices_vision_encoder_path, vision_encoder_pretrained=args.rices_vision_encoder_pretrained, ) else: # subset of the training set to sample context images from query_set = utils.get_query_set(train_dataset, args.query_set_size) utils.random_seed(seed, args.rank) predictions = [] for batch_idx, batch in tqdm( enumerate(test_dataloader), desc=f"Running inference {dataset_name}", disable=args.rank != 0, ): if args.rices: batch_demo_samples = rices_dataset.find(batch["image"], effective_num_shots) else: batch_demo_samples = utils.sample_batch_demos_from_query_set( query_set, effective_num_shots, len(batch["image"]) ) # set up prompt ensembling num_permutations = ( min(6, math.factorial(effective_num_shots)) if use_prompt_ensembling else 1 ) logprobs = [] for _ in range(num_permutations): batch_images, batch_text = [], [] for i in range(len(batch["image"])): if use_prompt_ensembling: random.shuffle(batch_demo_samples[i]) if effective_num_shots > 0: context_images = [x["image"] for x in batch_demo_samples[i]] else: context_images = [] batch_images.append(context_images + [batch["image"][i]]) context_text = "".join([prompt_fn(x) for x in batch_demo_samples[i]]) # Keep the text but remove the image tags for the zero-shot case if num_shots == 0: context_text = context_text.replace("<image>", "") batch_text.append( context_text + prompt_fn({"ocr": batch["ocr"][i], "class_name": None}) ) # get predicted class names logprobs.append( eval_model.get_rank_classifications( batch_text, batch_images, all_class_names, use_cache=(not no_kv_caching), normalize_length=True, ) ) # ensemble logprobs together logprobs = torch.mean(torch.stack(logprobs, dim=-1), dim=-1) predicted_classnames, predicted_logprobs = utils.get_predicted_classnames( logprobs, k, class_id_to_name, ) # compute accuracy for i, topk in enumerate(predicted_classnames): y_i = batch["class_name"][i] score = torch.exp( predicted_logprobs[i][0] - torch.logsumexp(logprobs[i], dim=0) ).item() predictions.append( { "id": batch["id"][i], "gt_label": y_i, "pred_label": topk[0], "pred_score": score, } ) # all gather all_predictions = [None for _ in range(args.world_size)] torch.distributed.all_gather_object(all_predictions, predictions) # list of lists if args.rank != 0: return all_predictions = [ item for sublist in all_predictions for item in sublist ] # flatten if dataset_name == "hateful_memes": # return ROC-AUC score greater_label = max(all_class_names) gts = [pred["gt_label"] for pred in all_predictions] pred_scores = [ pred["pred_score"] if pred["pred_label"] == greater_label else 1 - pred["pred_score"] for pred in all_predictions ] return roc_auc_score(gts, pred_scores) else: # return top-1 accuracy acc1 = sum( int(pred["gt_label"] == pred["pred_label"]) for pred in all_predictions ) return float(acc1) / len(all_predictions)
Evaluate a model on classification dataset. Args: eval_model (BaseEvalModel): model to evaluate seed (int, optional): random seed. Defaults to 42. num_shots (int, optional): number of shots to use. Defaults to 8. no_kv_caching (bool): whether to disable key-value caching dataset_name (str, optional): dataset name. Defaults to "imagenet". cached_features (tensor, optional): cached demonstration features for RICES. Defaults to None. Returns: float: accuracy score
20,230
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.fsdp._common_utils import ( _apply_to_modules, _FSDPState, _get_module_fsdp_state_if_fully_sharded_module, _get_param_to_fqns, _module_handles, clean_tensor_name, ) from torch.distributed.fsdp._fsdp_extensions import _ext_chunk_tensor from torch.distributed.fsdp._runtime_utils import _clear_grads_if_needed, _lazy_init from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.flat_param import FlatParameter, FlatParamHandle class _OptimStateKey(NamedTuple): """ This represents an optimizer state key that may be used commonly across ranks. It is based on the unflattened parameter names rather than parameter IDs to make it indepenendent of each rank's own optimizer construction. """ unflat_param_names: Tuple[str, ...] is_fsdp_managed: bool def _flatten_optim_state( fsdp_param_info: FSDPParamInfo, unflat_osd_state: Dict[str, Dict[str, Any]], unflat_param_names: List[str], shard_state: bool, ) -> Dict[str, Any]: """ Flattens the optimizer state in ``full_optim_state_dict`` for a single flattened parameter in ``fsdp_param_info`` corresponding to the unflattened parameter names in ``unflat_param_names``. Args: unflat_osd_state (Dict[str, Dict[str, Any]]): The "state" part of the optimizer state dict corresponding to the unflattened parameters. unflat_param_names (List[str]): A :class:`list` of unflattened parameter names corresponding to the flattened parameter ``flat_param``. fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten parameter. shard_state (bool): Whether to shard flattened positive-dimension tensor state; if ``False``, then the full flattened tensor is kept in the returned :class:`dict. Returns: Dict[str, Any]: A :class:`dict` mapping state names to their values for a particular flattened parameter. The sharded optimizer state dict's "state" part will map a key to this returned value. """ fsdp_state = fsdp_param_info.state flat_param = fsdp_param_info.flat_param num_unflat_params = len(unflat_param_names) assert num_unflat_params > 0, ( "Expects at least one unflattened parameter corresponding to the " "flattened parameter" ) unflat_param_shapes = flat_param._shapes num_unflat_param_shapes = len(unflat_param_shapes) assert ( num_unflat_params == num_unflat_param_shapes ), f"Expects {num_unflat_params} shapes but got {num_unflat_param_shapes}" # Check if these unflattened parameters have any optimizer state has_state = [ bool(unflat_param_name in unflat_osd_state) for unflat_param_name in unflat_param_names ] # If none of the unflattened parameters comprising this flattened parameter # have any state, then we do not want an entry in the optimizer state dict if not any(has_state): return {} # no need to flatten any state # There may still be some unflattened parameters with state and some # without unflat_param_states = [ _gather_state_dict( unflat_osd_state[unflat_param_name], pg=fsdp_state.process_group ) if unflat_param_name in unflat_osd_state else None for unflat_param_name in unflat_param_names ] # Check that the unflattened parameters have the same state names state_names = None for unflat_param_state in unflat_param_states: if unflat_param_state is None: continue if state_names is None: state_names = set(unflat_param_state.keys()) else: if state_names != set(unflat_param_state.keys()): raise ValueError( "Differing optimizer state names for the unflattened " f"parameters: {unflat_param_names}" ) assert state_names is not None # Flatten the state flat_state: Dict[str, Any] = {} for state_name in state_names: state_values = [ unflat_param_state[state_name] if unflat_param_state is not None else None for unflat_param_state in unflat_param_states ] non_none_state_values = [v for v in state_values if v is not None] are_pos_dim_tensors = are_zero_dim_tensors = are_non_tensors = True for v in non_none_state_values: are_pos_dim_tensors &= torch.is_tensor(v) and v.dim() > 0 are_zero_dim_tensors &= _is_zero_dim_tensor(v) are_non_tensors &= not torch.is_tensor(v) types = {type(v) for v in non_none_state_values} if len(types) != 1 or not ( are_pos_dim_tensors or are_zero_dim_tensors or are_non_tensors ): raise ValueError( f"Differing optimizer state types for state {state_name}, " f"values {non_none_state_values}, and unflattened parameter " f"names {unflat_param_names}" ) if are_pos_dim_tensors: flat_tensor = _flatten_tensor_optim_state( state_name, state_values, unflat_param_names, unflat_param_shapes, flat_param, ) if shard_state: # Shard the flattened tensor immediately to minimize max memory # usage sharded_flat_tensor, _ = FlatParamHandle._get_shard( flat_tensor, fsdp_state.rank, fsdp_state.world_size, ) flat_state[state_name] = sharded_flat_tensor else: flat_state[state_name] = flat_tensor elif are_zero_dim_tensors: flat_state[state_name] = _flatten_zero_dim_tensor_optim_state( state_name, state_values, unflat_param_names, ) else: assert are_non_tensors flat_state[state_name] = _flatten_non_tensor_optim_state( state_name, state_values, unflat_param_names, ) return flat_state def _get_fqn_to_fsdp_param_info(model: nn.Module) -> Dict[str, FSDPParamInfo]: """ Construct the mapping from a param's fqn to its corresponding ``FSDPParamInfo`` if the param is managed by FSDP. ``FlatParameter._fqns`` only stores the first FQN of a shared parameter. So the keys in the mapping are guaranteed to map to unique parameters. """ def module_fn(module, prefix, fqn_to_param_info): fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module) if fsdp_state is None: return _lazy_init(fsdp_state, module) handles = _module_handles(fsdp_state, module) if not handles: return flat_param = handles[0].flat_param fsdp_param_info = FSDPParamInfo(fsdp_state, flat_param, {}) for idx, local_fqn in enumerate(flat_param._fqns): fqn = clean_tensor_name(prefix + local_fqn) if fqn in fqn_to_param_info: assert fqn_to_param_info[fqn].flat_param == flat_param fqn_to_param_info[fqn] = fsdp_param_info fsdp_param_info.param_indices[fqn] = idx def return_fn(fqn_to_param_info): return fqn_to_param_info fqn_to_param_info: Dict[str, FSDPParamInfo] = {} # FlatParameter._fqns stores the local fqn, starting from the root of the # FSDP. Using _apply_to_modules() with model (may not be the FSDP root # module) allows us to construct the global fqn. return _apply_to_modules( model, module_fn, return_fn, [fqn for fqn, _ in model.named_parameters()], fqn_to_param_info, ) def _shard_orig_param_state( fsdp_param_info: FSDPParamInfo, fqn: str, optim_state: Dict[str, Any], ) -> Dict[str, Any]: """ Shard the optimizer state for the original parameter with the name ``fqn``. This API should only be used when ``use_orig_params`` is True. """ if not optim_state: return {} fsdp_state = fsdp_param_info.state flat_param = fsdp_param_info.flat_param param_idx = fsdp_param_info.param_indices[fqn] optim_state = _gather_state_dict(optim_state, fsdp_state.process_group) start, end = flat_param._shard_indices # type: ignore[attr-defined] if not (start <= param_idx <= end and flat_param._shard_param_offsets): # type: ignore[attr-defined] return {} param_start, param_end = flat_param._shard_param_offsets[param_idx - start] # type: ignore[attr-defined] # Flatten and shard the state. new_optim_state: Dict[str, Any] = {} for state_name, value in optim_state.items(): if torch.is_tensor(value) and value.dim() > 0: value = value.flatten()[param_start : param_end + 1] new_optim_state[state_name] = value return new_optim_state The provided code snippet includes necessary dependencies for implementing the `_flatten_optim_state_dict` function. Write a Python function `def _flatten_optim_state_dict( optim_state_dict: Dict[str, Any], model: nn.Module, shard_state: bool, use_orig_params: bool = False, optim: Optional[torch.optim.Optimizer] = None, ) -> Dict[str, Any]` to solve the following problem: Flattens the full optimizer state dict, still keying by unflattened parameter names. If ``shard_state=True``, then FSDP-managed ``FlatParameter`` 's optimizer states are sharded, and otherwise, they are kept unsharded. If ``use_orig_params`` is True, each rank will have all FSDP-managed parameters but some of these parameters may be empty due to the sharding. For a regular optim.Optimizer, states for those empty parameters will not be initialized. So, when aggregating the FQNs across ranks, no assert will be raised on a rank even if it does not have all the states -- it is valid and FSDP know how to aggregate them. However, FSDP has to ignore handling those parameters that are not managed by FSDP and do not exist on the local rank -- it is managed by other parallelism and FSDP does not know ho to handle/aggregate them. Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require all the states even if the corresponding parameters are empty. To this end, ``optim`` will be used to to get the initial state of the empty parameters. ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or NamedOptimizer. Returns: Dict[str, Any]: The flattened optimizer state dict. Here is the function: def _flatten_optim_state_dict( optim_state_dict: Dict[str, Any], model: nn.Module, shard_state: bool, use_orig_params: bool = False, optim: Optional[torch.optim.Optimizer] = None, ) -> Dict[str, Any]: """ Flattens the full optimizer state dict, still keying by unflattened parameter names. If ``shard_state=True``, then FSDP-managed ``FlatParameter`` 's optimizer states are sharded, and otherwise, they are kept unsharded. If ``use_orig_params`` is True, each rank will have all FSDP-managed parameters but some of these parameters may be empty due to the sharding. For a regular optim.Optimizer, states for those empty parameters will not be initialized. So, when aggregating the FQNs across ranks, no assert will be raised on a rank even if it does not have all the states -- it is valid and FSDP know how to aggregate them. However, FSDP has to ignore handling those parameters that are not managed by FSDP and do not exist on the local rank -- it is managed by other parallelism and FSDP does not know ho to handle/aggregate them. Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require all the states even if the corresponding parameters are empty. To this end, ``optim`` will be used to to get the initial state of the empty parameters. ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or NamedOptimizer. Returns: Dict[str, Any]: The flattened optimizer state dict. """ unflat_osd = optim_state_dict if "state" not in unflat_osd or "param_groups" not in unflat_osd: raise ValueError( '`optim_state_dict` must have the keys "state" and ' '"param_groups" to be a valid optimizer state dict' ) param_to_fqns = _get_param_to_fqns(model) fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model) # Construct the "state" part flat_osd_state: Dict[Union[_OptimStateKey, str], Any] = {} unflat_osd_state = unflat_osd["state"] all_state_keys = set(unflat_osd_state.keys()) # local_state_dict is used to construct states of empty parameters. # This should only be used if is_named_optimizer=True. local_state_dict: Dict[str, Any] = {} local_state_clean_fqns: Dict[str, str] = {} if optim is not None: local_state_dict = optim.state_dict()["state"] for fqn in local_state_dict.keys(): clean_fqn = clean_tensor_name(fqn) local_state_clean_fqns[clean_fqn] = fqn for param, unflat_param_names in param_to_fqns.items(): fqn = unflat_param_names[0] if fqn not in unflat_osd_state: continue all_state_keys.difference_update(unflat_param_names) if fqn in fqn_to_fsdp_param_info: fsdp_param_info = fqn_to_fsdp_param_info[fqn] if use_orig_params: assert ( shard_state ), "If use_orig_params is True, shard_state must be True." flat_state = _shard_orig_param_state( fsdp_param_info, fqn, unflat_osd_state[fqn], ) else: flat_state = _flatten_optim_state( fsdp_param_info, unflat_osd_state, unflat_param_names, shard_state, ) key = _OptimStateKey(tuple(unflat_param_names), True) # Only include non-empty states since as expected by # `torch.optim.Optimizer` s unless the optimizer is KeyedOptimizer # or NamedOptimizer. if flat_state: flat_osd_state[key] = flat_state elif optim is not None: # NamedOptimizer or KeyedOptimizer case. assert len(unflat_param_names) == 1 local_wrapped_fqn = local_state_clean_fqns.get(fqn, "") if local_wrapped_fqn: flat_osd_state[key] = copy.deepcopy( local_state_dict[local_wrapped_fqn] ) else: # do not flatten non-FSDP parameters' states assert len(unflat_param_names) == 1 key = _OptimStateKey(tuple(unflat_param_names), False) flat_osd_state[key] = copy.copy(unflat_osd_state[fqn]) # Handle user-defined state, states that are not accosiated with parameters. for key in all_state_keys: flat_osd_state[key] = copy.copy(unflat_osd_state[key]) # Construct the "param_groups" part -- copy as is since it will be # rekeyed later according to the target rank's optimizer flat_osd_param_groups = copy.deepcopy(unflat_osd["param_groups"]) return {"state": flat_osd_state, "param_groups": flat_osd_param_groups}
Flattens the full optimizer state dict, still keying by unflattened parameter names. If ``shard_state=True``, then FSDP-managed ``FlatParameter`` 's optimizer states are sharded, and otherwise, they are kept unsharded. If ``use_orig_params`` is True, each rank will have all FSDP-managed parameters but some of these parameters may be empty due to the sharding. For a regular optim.Optimizer, states for those empty parameters will not be initialized. So, when aggregating the FQNs across ranks, no assert will be raised on a rank even if it does not have all the states -- it is valid and FSDP know how to aggregate them. However, FSDP has to ignore handling those parameters that are not managed by FSDP and do not exist on the local rank -- it is managed by other parallelism and FSDP does not know ho to handle/aggregate them. Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require all the states even if the corresponding parameters are empty. To this end, ``optim`` will be used to to get the initial state of the empty parameters. ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or NamedOptimizer. Returns: Dict[str, Any]: The flattened optimizer state dict.
20,231
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.fsdp._common_utils import ( _apply_to_modules, _FSDPState, _get_module_fsdp_state_if_fully_sharded_module, _get_param_to_fqns, _module_handles, clean_tensor_name, ) from torch.distributed.fsdp._fsdp_extensions import _ext_chunk_tensor from torch.distributed.fsdp._runtime_utils import _clear_grads_if_needed, _lazy_init from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.flat_param import FlatParameter, FlatParamHandle def sorted_items(dictionary: Dict[str, Any]) -> Iterator[Tuple[str, Any]]: keys = sorted(dictionary.keys()) for k in keys: yield k, dictionary[k] class _PosDimTensorInfo(NamedTuple): """ Meatadata for positive-dimension tensors used internally for :meth:`scatter_full_optim_state_dict`. Attributes: shape (torch.Size): Sharded tensor shape (which is equal to the unsharded tensor shape if the tensor is optimizer state for a non-FSDP parameter and is hence not sharded). dtype (torch.dtype): Data type of the tensor. """ shape: torch.Size dtype: torch.dtype The provided code snippet includes necessary dependencies for implementing the `_process_pos_dim_tensor_state` function. Write a Python function `def _process_pos_dim_tensor_state( flat_optim_state_dict: Dict[str, Any], world_size: int, ) -> Dict[str, Any]` to solve the following problem: Processes positive-dimension tensor states in ``flat_optim_state_dict`` by replacing them with metadata. This is done so the processed optimizer state dict can be broadcast from rank 0 to all ranks without copying those tensor states, and thus, this is meant to only be called on rank 0. Args: flat_optim_state_dict (Dict[str, Any]): Flattened optimizer state dict with the positive-dimension tensor states unsharded. Returns: Dict[str, Any]: The flattened optimizer state dict with positive- dimension tensor states replaced by metadata. Here is the function: def _process_pos_dim_tensor_state( flat_optim_state_dict: Dict[str, Any], world_size: int, ) -> Dict[str, Any]: """ Processes positive-dimension tensor states in ``flat_optim_state_dict`` by replacing them with metadata. This is done so the processed optimizer state dict can be broadcast from rank 0 to all ranks without copying those tensor states, and thus, this is meant to only be called on rank 0. Args: flat_optim_state_dict (Dict[str, Any]): Flattened optimizer state dict with the positive-dimension tensor states unsharded. Returns: Dict[str, Any]: The flattened optimizer state dict with positive- dimension tensor states replaced by metadata. """ flat_osd = flat_optim_state_dict # alias no_tensor_osd: Dict[str, Any] = {"state": {}} for key, param_state in flat_osd["state"].items(): no_tensor_osd["state"][key] = {} for state_name, value in sorted_items(param_state): is_pos_dim_tensor_state = torch.is_tensor(value) and value.dim() > 0 if not is_pos_dim_tensor_state: no_tensor_osd["state"][key][state_name] = value continue if key.is_fsdp_managed: # FSDP parameter sharded_size = FlatParamHandle._get_sharded_size( value, rank=0, world_size=world_size ) assert len(sharded_size) == 1, f"{sharded_size}" info = _PosDimTensorInfo(sharded_size, value.dtype) else: # non-FSDP parameter info = _PosDimTensorInfo(value.shape, value.dtype) no_tensor_osd["state"][key][state_name] = info no_tensor_osd["param_groups"] = flat_osd["param_groups"] return no_tensor_osd
Processes positive-dimension tensor states in ``flat_optim_state_dict`` by replacing them with metadata. This is done so the processed optimizer state dict can be broadcast from rank 0 to all ranks without copying those tensor states, and thus, this is meant to only be called on rank 0. Args: flat_optim_state_dict (Dict[str, Any]): Flattened optimizer state dict with the positive-dimension tensor states unsharded. Returns: Dict[str, Any]: The flattened optimizer state dict with positive- dimension tensor states replaced by metadata.
20,232
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.fsdp._common_utils import ( _apply_to_modules, _FSDPState, _get_module_fsdp_state_if_fully_sharded_module, _get_param_to_fqns, _module_handles, clean_tensor_name, ) from torch.distributed.fsdp._fsdp_extensions import _ext_chunk_tensor from torch.distributed.fsdp._runtime_utils import _clear_grads_if_needed, _lazy_init from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.flat_param import FlatParameter, FlatParamHandle The provided code snippet includes necessary dependencies for implementing the `_broadcast_processed_optim_state_dict` function. Write a Python function `def _broadcast_processed_optim_state_dict( processed_optim_state_dict: Optional[Dict[str, Any]], rank: int, group, ) -> Dict[str, Any]` to solve the following problem: Broadcasts the processed optimizer state dict from rank 0 to all ranks. Args: processed_optim_state_dict (Optional[Dict[str, Any]]): The flattened optimizer state dict with positive-dimension tensor states replaced with metadata if on rank 0; ignored otherwise. Returns: Dict[str, Any]: The processed optimizer state dict. Here is the function: def _broadcast_processed_optim_state_dict( processed_optim_state_dict: Optional[Dict[str, Any]], rank: int, group, ) -> Dict[str, Any]: """ Broadcasts the processed optimizer state dict from rank 0 to all ranks. Args: processed_optim_state_dict (Optional[Dict[str, Any]]): The flattened optimizer state dict with positive-dimension tensor states replaced with metadata if on rank 0; ignored otherwise. Returns: Dict[str, Any]: The processed optimizer state dict. """ # Broadcast the two data structures rank 0 to all ranks obj_list = [processed_optim_state_dict] if rank == 0 else [None] dist.broadcast_object_list(obj_list, src=0, group=group) processed_optim_state_dict = obj_list[0] # type: ignore[assignment] assert processed_optim_state_dict is not None # Keep zero-dimension tensors on CPU return processed_optim_state_dict
Broadcasts the processed optimizer state dict from rank 0 to all ranks. Args: processed_optim_state_dict (Optional[Dict[str, Any]]): The flattened optimizer state dict with positive-dimension tensor states replaced with metadata if on rank 0; ignored otherwise. Returns: Dict[str, Any]: The processed optimizer state dict.
20,233
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.fsdp._common_utils import ( _apply_to_modules, _FSDPState, _get_module_fsdp_state_if_fully_sharded_module, _get_param_to_fqns, _module_handles, clean_tensor_name, ) from torch.distributed.fsdp._fsdp_extensions import _ext_chunk_tensor from torch.distributed.fsdp._runtime_utils import _clear_grads_if_needed, _lazy_init from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.flat_param import FlatParameter, FlatParamHandle def sorted_items(dictionary: Dict[str, Any]) -> Iterator[Tuple[str, Any]]: keys = sorted(dictionary.keys()) for k in keys: yield k, dictionary[k] class _PosDimTensorInfo(NamedTuple): """ Meatadata for positive-dimension tensors used internally for :meth:`scatter_full_optim_state_dict`. Attributes: shape (torch.Size): Sharded tensor shape (which is equal to the unsharded tensor shape if the tensor is optimizer state for a non-FSDP parameter and is hence not sharded). dtype (torch.dtype): Data type of the tensor. """ shape: torch.Size dtype: torch.dtype def _broadcast_sharded_pos_dim_tensor_state( unsharded_tensor: Optional[torch.Tensor], param_state: Dict[str, Any], state_name: str, shape: torch.Size, dtype: torch.dtype, broadcast_device: torch.device, rank: int, world_size: int, group, ) -> None: """ Broadcasts positive-dimension tensor state for the state ``state_name`` corresponding to an FSDP parameter shard-by-shard, only to be saved on the relevant rank. This modifies ``param_state`` destructively. Args: unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor from which to broadcast shards if on rank 0; ignored otherwise. shape (torch.Size): Shape of the sharded tensor; same on all ranks. """ get_shard: Optional[functools.partial[Tuple[torch.Tensor, int]]] = None if rank == 0: assert ( unsharded_tensor is not None ), "Expects rank 0 to pass in the unsharded tensor" get_shard = functools.partial( FlatParamHandle._get_shard, unsharded_tensor, ) for target_rank in range(1, world_size): if rank == 0: assert get_shard is not None sharded_tensor = get_shard(target_rank, world_size)[0].to(broadcast_device) else: sharded_tensor = torch.zeros( shape, requires_grad=False, dtype=dtype, device=broadcast_device, ) dist.broadcast(sharded_tensor, src=0, group=group) # Only keep the shard on the target rank and keep it on the broadcast # device, which is typically GPU if rank == target_rank: param_state[state_name] = sharded_tensor else: del sharded_tensor # Lastly, shard on rank 0 if rank != 0: return param_state[state_name] = get_shard(0, world_size)[0].to(broadcast_device) # type: ignore[misc] def _broadcast_unsharded_pos_dim_tensor_state( unsharded_tensor: Optional[torch.Tensor], param_state: Dict[str, Any], state_name: str, shape: torch.Size, dtype: torch.dtype, broadcast_device: torch.device, rank: int, group, ) -> None: """ Broadcasts positive-dimension tensor state for the state ``state_name`` corresponding to an unsharded non-FSDP parameter from rank 0 to all ranks. This modifies ``param_state`` destructively. Args: unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor to broadcast if on rank 0; ignored otherwise. """ if rank == 0: assert ( unsharded_tensor is not None ), "Expects rank 0 to pass in the unsharded tensor" assert ( shape == unsharded_tensor.shape ), f"Shape mismatch: {shape} {unsharded_tensor.shape}" assert ( dtype == unsharded_tensor.dtype ), f"dtype mismatch: {dtype} {unsharded_tensor.dtype}" unsharded_tensor = unsharded_tensor.to(broadcast_device) else: unsharded_tensor = torch.zeros( shape, requires_grad=False, dtype=dtype, device=broadcast_device, ) dist.broadcast(unsharded_tensor, src=0, group=group) # Keep the tensor on the broadcast device, which is typically GPU param_state[state_name] = unsharded_tensor The provided code snippet includes necessary dependencies for implementing the `_broadcast_pos_dim_tensor_states` function. Write a Python function `def _broadcast_pos_dim_tensor_states( processed_optim_state_dict: Dict[str, Any], flat_optim_state_dict: Optional[Dict[str, Any]], rank: int, world_size: int, group, broadcast_device: torch.device, ) -> Dict[str, Any]` to solve the following problem: Takes ``processed_optim_state_dict``, which has metadata in place of positive-dimension tensor states, and broadcasts those tensor states from rank 0 to all ranks. For tensor states corresponding to FSDP parameters, rank 0 shards the tensor and broadcasts shard-by-shard, and for tensor states corresponding to non-FSDP parameters, rank 0 broadcasts the full tensor. Args: processed_optim_state_dict (Dict[str, Any]): The flattened optimizer state dict with positive-dimension tensor states replaced with metadata; this should be returned by :meth:`_process_pos_dim_tensor_state` and non-empty on all ranks. flat_optim_state_dict (Optional[Dict[str, Any]]): The flattened unsharded optimizer state dict with the actual positive-dimension tensor states if on rank 0; ignored on nonzero ranks. Returns: Dict[str, Any]: The optimizer state dict with the positive-dimension tensor state correctly populated via ``broadcast()`` s from rank 0. Here is the function: def _broadcast_pos_dim_tensor_states( processed_optim_state_dict: Dict[str, Any], flat_optim_state_dict: Optional[Dict[str, Any]], rank: int, world_size: int, group, broadcast_device: torch.device, ) -> Dict[str, Any]: """ Takes ``processed_optim_state_dict``, which has metadata in place of positive-dimension tensor states, and broadcasts those tensor states from rank 0 to all ranks. For tensor states corresponding to FSDP parameters, rank 0 shards the tensor and broadcasts shard-by-shard, and for tensor states corresponding to non-FSDP parameters, rank 0 broadcasts the full tensor. Args: processed_optim_state_dict (Dict[str, Any]): The flattened optimizer state dict with positive-dimension tensor states replaced with metadata; this should be returned by :meth:`_process_pos_dim_tensor_state` and non-empty on all ranks. flat_optim_state_dict (Optional[Dict[str, Any]]): The flattened unsharded optimizer state dict with the actual positive-dimension tensor states if on rank 0; ignored on nonzero ranks. Returns: Dict[str, Any]: The optimizer state dict with the positive-dimension tensor state correctly populated via ``broadcast()`` s from rank 0. """ assert ( rank != 0 or flat_optim_state_dict is not None ), "Expects rank 0 to pass in the flattened optimizer state dict" no_tensor_osd = processed_optim_state_dict # alias flat_osd = flat_optim_state_dict # alias for key, param_state in no_tensor_osd["state"].items(): for state_name, value in sorted_items(param_state): is_pos_dim_tensor_state = isinstance(value, _PosDimTensorInfo) if not is_pos_dim_tensor_state: continue if rank == 0: assert flat_osd is not None unsharded_tensor = flat_osd["state"][key][state_name] else: unsharded_tensor = None shape, dtype = value.shape, value.dtype if key.is_fsdp_managed: # FSDP parameter _broadcast_sharded_pos_dim_tensor_state( unsharded_tensor, param_state, state_name, shape, dtype, broadcast_device, rank, world_size, group, ) # modify `param_state` destructively else: # non-FSDP parameter _broadcast_unsharded_pos_dim_tensor_state( unsharded_tensor, param_state, state_name, shape, dtype, broadcast_device, rank, group, ) # modify `param_state` destructively return no_tensor_osd
Takes ``processed_optim_state_dict``, which has metadata in place of positive-dimension tensor states, and broadcasts those tensor states from rank 0 to all ranks. For tensor states corresponding to FSDP parameters, rank 0 shards the tensor and broadcasts shard-by-shard, and for tensor states corresponding to non-FSDP parameters, rank 0 broadcasts the full tensor. Args: processed_optim_state_dict (Dict[str, Any]): The flattened optimizer state dict with positive-dimension tensor states replaced with metadata; this should be returned by :meth:`_process_pos_dim_tensor_state` and non-empty on all ranks. flat_optim_state_dict (Optional[Dict[str, Any]]): The flattened unsharded optimizer state dict with the actual positive-dimension tensor states if on rank 0; ignored on nonzero ranks. Returns: Dict[str, Any]: The optimizer state dict with the positive-dimension tensor state correctly populated via ``broadcast()`` s from rank 0.
20,234
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.fsdp._common_utils import ( _apply_to_modules, _FSDPState, _get_module_fsdp_state_if_fully_sharded_module, _get_param_to_fqns, _module_handles, clean_tensor_name, ) from torch.distributed.fsdp._fsdp_extensions import _ext_chunk_tensor from torch.distributed.fsdp._runtime_utils import _clear_grads_if_needed, _lazy_init from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.flat_param import FlatParameter, FlatParamHandle def _get_flat_param_to_fqn(model: torch.nn.Module) -> Dict[nn.Parameter, str]: def module_fn(module, prefix, flat_param_to_fqn): for param_name, param in module.named_parameters(recurse=False): if type(param) is not FlatParameter: continue fqn = clean_tensor_name(prefix + param_name) flat_param_to_fqn[param] = fqn def return_fn(flat_param_to_fqn): return flat_param_to_fqn flat_param_to_fqn_ret: Dict[torch.nn.Parameter, str] = {} return _apply_to_modules( model, module_fn, return_fn, [fqn for fqn, _ in model.named_parameters()], flat_param_to_fqn_ret, ) def _get_param_to_param_key( optim: torch.optim.Optimizer, model: Optional[nn.Module] = None, is_named_optimizer: bool = False, param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None, flat_param_to_fqn: Optional[Dict[nn.Parameter, str]] = None, ) -> Dict[nn.Parameter, Union[int, str]]: """ Constructs the inverse mapping of :func:`_get_param_key_to_param`. This API only supports the case where `optim` is a regular optimizer, not NamedOptimizer. So the parameter keys will be parameter id. """ param_id_to_param = _get_param_key_to_param( optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn ) return {param: param_id for param_id, param in param_id_to_param.items()} def _get_param_to_param_id_from_optim_input( model: nn.Module, optim_input: Optional[ Union[ List[Dict[str, Any]], Iterable[nn.Parameter], ] ] = None, ) -> Dict[nn.Parameter, int]: """Constructs the inverse mapping of :func:`_get_param_id_to_param_from_optim_input`.""" param_id_to_param = _get_param_id_to_param_from_optim_input(model, optim_input) return {param: param_id for param_id, param in param_id_to_param.items()} The provided code snippet includes necessary dependencies for implementing the `_rekey_sharded_optim_state_dict` function. Write a Python function `def _rekey_sharded_optim_state_dict( sharded_osd: Dict[str, Any], model: nn.Module, optim: torch.optim.Optimizer, optim_input: Optional[ Union[ List[Dict[str, Any]], Iterable[nn.Parameter], ] ], using_optim_input: bool, is_named_optimizer: bool = False, ) -> Dict[str, Any]` to solve the following problem: Rekeys the optimizer state dict from unflattened parameter names to flattened parameter IDs according to the calling rank's ``optim``, which may be different across ranks. In particular, the unflattened parameter names are represented as :class:`_OptimStateKey` s. Here is the function: def _rekey_sharded_optim_state_dict( sharded_osd: Dict[str, Any], model: nn.Module, optim: torch.optim.Optimizer, optim_input: Optional[ Union[ List[Dict[str, Any]], Iterable[nn.Parameter], ] ], using_optim_input: bool, is_named_optimizer: bool = False, ) -> Dict[str, Any]: """ Rekeys the optimizer state dict from unflattened parameter names to flattened parameter IDs according to the calling rank's ``optim``, which may be different across ranks. In particular, the unflattened parameter names are represented as :class:`_OptimStateKey` s. """ param_to_fqns = _get_param_to_fqns(model) flat_param_to_fqn = _get_flat_param_to_fqn(model) param_to_param_key: Dict[nn.Parameter, Union[int, str]] = cast( Dict[nn.Parameter, Union[int, str]], ( _get_param_to_param_id_from_optim_input(model, optim_input) if using_optim_input else _get_param_to_param_key( optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn ) ), ) # All parameter keys in `param_to_param_key` should be in # `param_to_fqns` -- strict inequality follows when not all parameters are # passed to the optimizer assert len(param_to_param_key) <= len(param_to_fqns) unflat_param_names_to_flat_param_key: Dict[ Tuple[str, ...], Union[int, str] ] = {} # for "state" unflat_param_name_to_flat_param_key: Dict[ str, Union[int, str] ] = {} # for "param_groups" for param, unflat_param_names in param_to_fqns.items(): if param not in param_to_param_key: # This parameter was not passed to the optimizer continue flat_param_key = param_to_param_key[param] unflat_param_names_to_flat_param_key[tuple(unflat_param_names)] = flat_param_key for unflat_param_name in unflat_param_names: unflat_param_name_to_flat_param_key[unflat_param_name] = flat_param_key sharded_osd_state = sharded_osd["state"] rekeyed_osd_state: Dict[Union[str, int], Any] = {} for key, param_state in sharded_osd_state.items(): if isinstance(key, str): rekeyed_osd_state[key] = param_state continue flat_param_key = unflat_param_names_to_flat_param_key.get( key.unflat_param_names, key.unflat_param_names ) rekeyed_osd_state[flat_param_key] = param_state rekeyed_osd_param_groups: List[Dict[str, Any]] = [] for unflat_param_group in sharded_osd["param_groups"]: flat_param_group = copy.deepcopy(unflat_param_group) flat_param_keys = sorted( { unflat_param_name_to_flat_param_key[unflat_param_name] for unflat_param_name in unflat_param_group["params"] } ) flat_param_group["params"] = flat_param_keys rekeyed_osd_param_groups.append(flat_param_group) return {"state": rekeyed_osd_state, "param_groups": rekeyed_osd_param_groups}
Rekeys the optimizer state dict from unflattened parameter names to flattened parameter IDs according to the calling rank's ``optim``, which may be different across ranks. In particular, the unflattened parameter names are represented as :class:`_OptimStateKey` s.
20,235
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.fsdp._common_utils import ( _apply_to_modules, _FSDPState, _get_module_fsdp_state_if_fully_sharded_module, _get_param_to_fqns, _module_handles, clean_tensor_name, ) from torch.distributed.fsdp._fsdp_extensions import _ext_chunk_tensor from torch.distributed.fsdp._runtime_utils import _clear_grads_if_needed, _lazy_init from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.flat_param import FlatParameter, FlatParamHandle def sorted_items(dictionary: Dict[str, Any]) -> Iterator[Tuple[str, Any]]: keys = sorted(dictionary.keys()) for k in keys: yield k, dictionary[k] def _unflatten_optim_state( fsdp_param_info: FSDPParamInfo, flat_param_state: Dict[str, Any], to_save: bool, shard_state: bool, ) -> List[Dict[str, Any]]: """ Unflattens the optimizer state, consisting of the "state" part and the "param_groups" part. Unflattening the "state" part involves consolidating the state on the target rank and remapping from flattened to unflattened parameter IDs, and the "param_groups" part only involves remapping from flattened to unflattened parameter IDs. Args: fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten parameter. flat_param_state (Dict[str, Any]): Entry for the flattened parameter in the "state" part of the optimizer state dict. to_save (bool): Whether to save the state on this rank. Returns: List[Dict[str, Any]]: A :class:`list` holding the entries in the "state" part of the optimizer state dict corresponding to the unflattened parameters comprising the flattened parameter if on the target rank or an empty :class:`list` otherwise. The final optimizer state dict will need to map these entries using the proper unflattened parameter IDs. """ assert ( not shard_state or to_save ), "If ``shard_state`` is True, ``to_save`` has to be True." consolidated_state = _communicate_optim_state( fsdp_param_info, flat_param_state, ) if to_save: unflat_param_state = _unflatten_communicated_optim_state( fsdp_param_info, consolidated_state, shard_state, ) for optim_state in unflat_param_state: for key in list(optim_state.keys()): state = optim_state[key] if isinstance(state, torch.Tensor): optim_state[key] = state.cpu() return unflat_param_state else: return [] def _get_param_id_to_param_from_optim_input( model: nn.Module, optim_input: Optional[ Union[ List[Dict[str, Any]], Iterable[nn.Parameter], ] ] = None, ) -> Dict[int, nn.Parameter]: """ Constructs a mapping from parameter IDs to parameters. This may be used both for models with ``FlatParameter`` s and without. NOTE: This method is only preserved for backward compatibility. The method :meth:`_get_param_key_to_param` is the preferred code path that does not rely on ``optim_input``. NOTE: We critically assume that, whether the optimizer input is a list of parameters or a list of parameter groups, :class:`torch.optim.Optimizer` enumerates the parameter IDs in order. In other words, for a parameter list input, the parameter IDs should be in that list order, and for a parameter groups input, the parameter IDs should be in order within each parameter group and in order across parameter groups. Args: model (nn.Module): Model whose parameters are passed into the optimizer. optim_input (Optional[Union[List[Dict[str, Any]], Iterable[nn.Parameter]]]): Input passed into the optimizer representing either a :class:`list` of parameter groups or an iterable of parameters; if ``None``, then this method assumes the input was ``model.parameters()``. (Default: ``None``) Returns: List[nn.Parameter]: Mapping from parameter IDs to parameters, where the parameter ID is implicitly the index in the :class:`list`. """ # Assume the standard case of passing `model.parameters()` to the optimizer # if `optim_input` is not specified if optim_input is None: return {pid: param for pid, param in enumerate(model.parameters())} try: params = cast(List[nn.Parameter], list(optim_input)) except TypeError as e: raise TypeError( "Optimizer input should be an iterable of Tensors or dicts, " f"but got {optim_input}" ) from e if len(params) == 0: raise ValueError("Optimizer input should not be empty") # Check if the optimizer input represents tensors or parameter groups all_tensors = True all_dicts = True for param in params: all_tensors &= isinstance(param, torch.Tensor) all_dicts &= isinstance(param, dict) if not all_tensors and not all_dicts: raise TypeError("Optimizer input should be an iterable of Tensors or dicts") if all_tensors: return {pid: param for pid, param in enumerate(params)} assert all_dicts param_id_to_param: List[nn.Parameter] = [] for param_group in params: has_params_key = "params" in param_group # type: ignore[operator] assert has_params_key, ( 'A parameter group should map "params" to a list of the ' "parameters in the group" ) for param in param_group["params"]: # type: ignore[index] # Implicitly map `flat_param_id` (current length of the list) to # `param` param_id_to_param.append(param) return {pid: param for pid, param in enumerate(param_id_to_param)} def _get_flat_param_to_fqn(model: torch.nn.Module) -> Dict[nn.Parameter, str]: def module_fn(module, prefix, flat_param_to_fqn): for param_name, param in module.named_parameters(recurse=False): if type(param) is not FlatParameter: continue fqn = clean_tensor_name(prefix + param_name) flat_param_to_fqn[param] = fqn def return_fn(flat_param_to_fqn): return flat_param_to_fqn flat_param_to_fqn_ret: Dict[torch.nn.Parameter, str] = {} return _apply_to_modules( model, module_fn, return_fn, [fqn for fqn, _ in model.named_parameters()], flat_param_to_fqn_ret, ) def _get_param_key_to_param( optim: torch.optim.Optimizer, model: Optional[nn.Module] = None, is_named_optimizer: bool = False, param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None, flat_param_to_fqn: Optional[Dict[nn.Parameter, str]] = None, ) -> Dict[Union[int, str], nn.Parameter]: """ Constructs a mapping from parameter keys to parameters. For the regular optimizers, the keys are parameter IDs. For NamedOptimizer, the keys are FQNs. This API may be used both for models with ``FlatParameter`` s and without. """ clean_fqn_to_curr_fqn: Dict[str, str] = {} if is_named_optimizer: assert ( param_to_fqns is not None and flat_param_to_fqn is not None ), "The optimizer is a NamedOptimizer, `param_to_fqns` must not be None." assert model is not None for key, _ in model.named_parameters(): clean_fqn_to_curr_fqn[clean_tensor_name(key)] = key param_key_to_param: Dict[Union[str, int], nn.Parameter] = {} pid = 0 for param_group in optim.param_groups: if is_named_optimizer: for param in param_group["params"]: assert flat_param_to_fqn is not None if param in flat_param_to_fqn: # FlatParameter case key = flat_param_to_fqn[param] else: assert param_to_fqns is not None # use_orig_params case assert len(param_to_fqns[param]) == 1 key = param_to_fqns[param][0] key = clean_fqn_to_curr_fqn[key] param_key_to_param[key] = param else: for param in param_group["params"]: param_key_to_param[pid] = param pid += 1 return param_key_to_param def _map_param_key_to_optim_keys( optim_state_dict: Dict[str, Any], group: Optional[dist.ProcessGroup], param_key_to_param: Dict[Union[int, str], nn.Parameter], param_to_fqns: Dict[nn.Parameter, List[str]], fqn_to_fsdp_param_info: Dict[str, FSDPParamInfo], merge_keys: bool = False, ) -> Tuple[List[_OptimStateKey], Dict[_OptimStateKey, Union[int, str]]]: """ Construct the local mapping between the ``_OptimStateKey`` and parameter keys and all the ``_OptimStateKey`` across ranks. If ``merge_keys`` is False, rank0 must contain all the ``_OptimStateKey``, an exception will be raised otherwise. Note that ``merge_keys`` should equal to ``use_orig_params``. """ rank = dist.get_rank(group) optim_state_key_to_param_key: Dict[_OptimStateKey, Union[int, str]] = {} # local all_optim_state_keys: List[_OptimStateKey] = [] for param_key, param in param_key_to_param.items(): # Do not include parameters without state to avoid empty mappings # just like in normal `torch.optim.Optimizer.state_dict()` if param_key not in optim_state_dict["state"]: continue fqns = param_to_fqns[param] is_fsdp_managed = isinstance(param, FlatParameter) if is_fsdp_managed: assert fqns[0] in fqn_to_fsdp_param_info, ( fqns[0], list(fqn_to_fsdp_param_info.keys()), ) is_fsdp_managed = fqns[0] in fqn_to_fsdp_param_info optim_state_key = _OptimStateKey( unflat_param_names=tuple(fqns), is_fsdp_managed=is_fsdp_managed, ) if rank == 0 or merge_keys: all_optim_state_keys.append(optim_state_key) optim_state_key_to_param_key[optim_state_key] = param_key if merge_keys: all_keys: List[List[_OptimStateKey]] = [ [] for _ in range(dist.get_world_size(group)) ] dist.all_gather_object(all_keys, all_optim_state_keys, group=group) merge_all_optim_state_keys = [ key for local_keys in all_keys for key in local_keys ] all_optim_state_keys = sorted(set(merge_all_optim_state_keys)) else: key_obj_list: List[Optional[List[_OptimStateKey]]] = ( [all_optim_state_keys] if rank == 0 else [None] ) dist.broadcast_object_list(key_obj_list, src=0, group=group) assert key_obj_list[0] is not None all_optim_state_keys = key_obj_list[0] _check_missing_keys_on_rank( all_optim_state_keys, optim_state_key_to_param_key, param_key_to_param, group, ) return all_optim_state_keys, optim_state_key_to_param_key def _unflatten_param_groups( state_dict: Dict[str, Any], param_key_to_param: Dict[Union[int, str], nn.Parameter], param_to_fqns: Dict[nn.Parameter, List[str]], ) -> List[Dict[str, Any]]: param_groups: List[Dict[str, Any]] = [] for flat_param_group in state_dict["param_groups"]: unflat_param_group = copy.deepcopy(flat_param_group) param_group_params = [ param_key_to_param[flat_param_key] for flat_param_key in flat_param_group["params"] ] nested_unflat_param_names = [ param_to_fqns[param] for param in param_group_params ] unflat_param_group["params"] = [ unflat_param_name for unflat_param_names in nested_unflat_param_names for unflat_param_name in unflat_param_names ] # flatten the list of lists param_groups.append(unflat_param_group) return param_groups def _is_named_optimizer(optim_state_dict: Dict[str, Any]) -> bool: state = optim_state_dict.get("state", None) if not state: # If we cannot find a state, assume it is not NamedOptimizer as # NamedOptimizer has eagerly initialization. return False try: key = next(iter(state.keys())) except Exception as e: raise Exception(optim_state_dict) from e return isinstance(key, str) def _get_fqn_to_fsdp_param_info(model: nn.Module) -> Dict[str, FSDPParamInfo]: """ Construct the mapping from a param's fqn to its corresponding ``FSDPParamInfo`` if the param is managed by FSDP. ``FlatParameter._fqns`` only stores the first FQN of a shared parameter. So the keys in the mapping are guaranteed to map to unique parameters. """ def module_fn(module, prefix, fqn_to_param_info): fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module) if fsdp_state is None: return _lazy_init(fsdp_state, module) handles = _module_handles(fsdp_state, module) if not handles: return flat_param = handles[0].flat_param fsdp_param_info = FSDPParamInfo(fsdp_state, flat_param, {}) for idx, local_fqn in enumerate(flat_param._fqns): fqn = clean_tensor_name(prefix + local_fqn) if fqn in fqn_to_param_info: assert fqn_to_param_info[fqn].flat_param == flat_param fqn_to_param_info[fqn] = fsdp_param_info fsdp_param_info.param_indices[fqn] = idx def return_fn(fqn_to_param_info): return fqn_to_param_info fqn_to_param_info: Dict[str, FSDPParamInfo] = {} # FlatParameter._fqns stores the local fqn, starting from the root of the # FSDP. Using _apply_to_modules() with model (may not be the FSDP root # module) allows us to construct the global fqn. return _apply_to_modules( model, module_fn, return_fn, [fqn for fqn, _ in model.named_parameters()], fqn_to_param_info, ) def _gather_orig_param_state( fsdp_param_info: FSDPParamInfo, fqn: str, optim_state: Dict[str, Any], shard_state: bool, group=None, ) -> Dict[str, Any]: """ Gather the optimizer state for the original parameter with the name ``fqn``. This API should only be used when ``use_orig_params`` is True. """ fsdp_state = fsdp_param_info.state assert ( fsdp_state._use_orig_params ), "_gather_orig_param_state only support use_orig_params=True case" flat_param = fsdp_param_info.flat_param param_idx = fsdp_param_info.param_indices[fqn] if ( fsdp_state.world_size == 1 or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD ): return optim_state gathered_state = _all_gather_optim_state(fsdp_state, optim_state, group=group) # Unflatten state values. for state_name, value in list(gathered_state.items()): if not torch.is_tensor(value) or value.dim() == 0: continue value = value[: flat_param._numels[param_idx]].reshape( flat_param._shapes[param_idx] ) if shard_state: assert fsdp_state.process_group is not None value = _ext_chunk_tensor( value, fsdp_state.rank, fsdp_state.world_size, torch.cuda.device_count(), fsdp_state.process_group, ) value = value.cpu() gathered_state[state_name] = value return gathered_state The provided code snippet includes necessary dependencies for implementing the `_optim_state_dict` function. Write a Python function `def _optim_state_dict( model: nn.Module, optim: torch.optim.Optimizer, optim_state_dict: Dict[str, Any], optim_input: Optional[ Union[ List[Dict[str, Any]], Iterable[nn.Parameter], ] ], rank0_only: bool, shard_state: bool, group: Optional[dist.ProcessGroup], using_optim_input: bool, use_orig_params: bool = False, ) -> Dict[str, Any]` to solve the following problem: Consolidates the optimizer state and returns it as a :class:`dict` following the convention of :meth:`torch.optim.Optimizer.state_dict`, i.e. with keys ``"state"`` and ``"param_groups"``. The flattened parameters in ``FSDP`` modules contained in ``model`` are mapped back to their unflattened parameters. Parameter keys are not well-defined. For a regular optimizer, the optimizer state_dict contains a mapping from parameter IDs to parameter states. Parameter IDs are the order of parameters in ``optim.param_groups()`` across all the groups. This API also allows user to pass ``optim_input`` for the mapping between parameters and parameter IDs. Using ``optim_input`` is being deprecated. If the optimizer is a ``NamedOptimizer``, the optimizer state_dict does not contain parameter IDs mapping but a mapping from parameter FQNs to parameter states. This API finds the mapping from FQNs to parameters if the optimizer is a ``NamedOptimizer``. If ``use_orig_params`` is True, each rank will have all FSDP-managed parameters but some of these parameters may be empty due to the sharding. For a regular optim.Optimizer, states for those empty parameters will not be initialized. So, when aggregating the FQNs across ranks, no assert will be raised on a rank even if it does not have all the states -- it is valid and FSDP know how to aggregate them. However, FSDP has to ignore handling those parameters that are not managed by FSDP and do not exist on the local rank -- it is managed by other parallelism and FSDP does not know ho to handle/aggregate them. Args: model (nn.Module): Root module (which may or may not be a :class:`FullyShardedDataParallel` instance) whose parameters were passed into the optimizer ``optim``. optim (torch.optim.Optimizer): Optimizer for ``model`` 's parameters. rank0_only (bool): If ``True``, saves the populated :class:`dict` only on rank 0; if ``False``, saves it on all ranks. (Default: ``True``) shard_state (bool): If ``True``, shard and distribute all non-zero-dimension states. Returns: Dict[str, Any]: A :class:`dict` containing the optimizer state for ``model`` 's original unflattened parameters and including keys "state" and "param_groups" following the convention of :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``, then nonzero ranks return an empty :class:`dict`. Here is the function: def _optim_state_dict( model: nn.Module, optim: torch.optim.Optimizer, optim_state_dict: Dict[str, Any], optim_input: Optional[ Union[ List[Dict[str, Any]], Iterable[nn.Parameter], ] ], rank0_only: bool, shard_state: bool, group: Optional[dist.ProcessGroup], using_optim_input: bool, use_orig_params: bool = False, ) -> Dict[str, Any]: """ Consolidates the optimizer state and returns it as a :class:`dict` following the convention of :meth:`torch.optim.Optimizer.state_dict`, i.e. with keys ``"state"`` and ``"param_groups"``. The flattened parameters in ``FSDP`` modules contained in ``model`` are mapped back to their unflattened parameters. Parameter keys are not well-defined. For a regular optimizer, the optimizer state_dict contains a mapping from parameter IDs to parameter states. Parameter IDs are the order of parameters in ``optim.param_groups()`` across all the groups. This API also allows user to pass ``optim_input`` for the mapping between parameters and parameter IDs. Using ``optim_input`` is being deprecated. If the optimizer is a ``NamedOptimizer``, the optimizer state_dict does not contain parameter IDs mapping but a mapping from parameter FQNs to parameter states. This API finds the mapping from FQNs to parameters if the optimizer is a ``NamedOptimizer``. If ``use_orig_params`` is True, each rank will have all FSDP-managed parameters but some of these parameters may be empty due to the sharding. For a regular optim.Optimizer, states for those empty parameters will not be initialized. So, when aggregating the FQNs across ranks, no assert will be raised on a rank even if it does not have all the states -- it is valid and FSDP know how to aggregate them. However, FSDP has to ignore handling those parameters that are not managed by FSDP and do not exist on the local rank -- it is managed by other parallelism and FSDP does not know ho to handle/aggregate them. Args: model (nn.Module): Root module (which may or may not be a :class:`FullyShardedDataParallel` instance) whose parameters were passed into the optimizer ``optim``. optim (torch.optim.Optimizer): Optimizer for ``model`` 's parameters. rank0_only (bool): If ``True``, saves the populated :class:`dict` only on rank 0; if ``False``, saves it on all ranks. (Default: ``True``) shard_state (bool): If ``True``, shard and distribute all non-zero-dimension states. Returns: Dict[str, Any]: A :class:`dict` containing the optimizer state for ``model`` 's original unflattened parameters and including keys "state" and "param_groups" following the convention of :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``, then nonzero ranks return an empty :class:`dict`. """ _clear_grads_if_needed(traversal_utils._get_fsdp_handles(model)) to_save = not rank0_only or (dist.get_rank(group) == 0 or shard_state) fsdp_osd: Dict[str, Any] = {"state": {}, "param_groups": []} if to_save else {} fsdp_osd_state: Dict[str, Any] = fsdp_osd["state"] if to_save else {} param_to_fqns = _get_param_to_fqns(model) flat_param_to_fqn = _get_flat_param_to_fqn(model) is_named_optimizer = _is_named_optimizer(optim_state_dict) param_key_to_param = cast( Dict[Union[int, str], nn.Parameter], ( _get_param_id_to_param_from_optim_input(model, optim_input) if using_optim_input else _get_param_key_to_param( optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn ) ), ) fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model) all_optim_state_keys, optim_state_key_to_param_key = _map_param_key_to_optim_keys( optim_state_dict, group, param_key_to_param, param_to_fqns, fqn_to_fsdp_param_info, merge_keys=use_orig_params, ) # Iterate in rank 0's flattened parameter ID order to ensure aligned # all-gathers across ranks for optim_state_key in all_optim_state_keys: param_key: Union[str, int, None] = optim_state_key_to_param_key.get( optim_state_key, None ) if param_key is None: assert use_orig_params, ( "If use_orig_params is False, we must be able to find the " f"corresponding param id. {optim_state_key} {param_key}" ) if not optim_state_key.is_fsdp_managed: continue if optim_state_key.is_fsdp_managed: # If there are multiple unflat_param_names (not use_orig_params), # they share the same FSDPParamInfo. So the first unflat_param_name # is sufficient to fetch the FSDPParamInfo. fqn = optim_state_key.unflat_param_names[0] fsdp_param_info = fqn_to_fsdp_param_info[fqn] if use_orig_params: state = ( {} if param_key is None else optim_state_dict["state"][param_key] ) unflat_state = [ _gather_orig_param_state( fsdp_param_info, fqn, state, shard_state, group ) ] else: unflat_state = _unflatten_optim_state( fsdp_param_info, optim_state_dict["state"][param_key], to_save, shard_state, ) if to_save: assert len(unflat_state) == len(optim_state_key.unflat_param_names) for unflat_param_name, unflat_param_state in zip( optim_state_key.unflat_param_names, unflat_state, ): fsdp_osd_state[unflat_param_name] = unflat_param_state elif to_save: assert len(optim_state_key.unflat_param_names) == 1 unflat_param_name = optim_state_key.unflat_param_names[0] fsdp_osd_state[unflat_param_name] = copy.copy( optim_state_dict["state"][param_key] ) for state_name, value in sorted_items(fsdp_osd_state[unflat_param_name]): if torch.is_tensor(value): fsdp_osd_state[unflat_param_name][state_name] = value.cpu() if to_save: flat_param_fqns = set(flat_param_to_fqn.values()) for key, value in optim_state_dict["state"].items(): if key in fsdp_osd_state: continue if key in flat_param_fqns: continue if key in param_key_to_param: continue # This key is not recognized by FSDP. It may be a user-defined state # or some parameters state that FSDP is unable to map from # ``optim.param_groups``. warnings.warn( f"Found a optim state, {key}, that FSDP cannot process. FSDP " "will directly copy everything to the returned state_dict. In " "most cases, this is a user-defined state that is not " "associated with any particular parameter. Another possible " "case is this state is managed by DMP. Otherwise, there may " " be a mismatched assumption of optim_state_dict of this mode." ) fsdp_osd_state[key] = value fsdp_osd["param_groups"] = _unflatten_param_groups( optim_state_dict, param_key_to_param, param_to_fqns ) return fsdp_osd
Consolidates the optimizer state and returns it as a :class:`dict` following the convention of :meth:`torch.optim.Optimizer.state_dict`, i.e. with keys ``"state"`` and ``"param_groups"``. The flattened parameters in ``FSDP`` modules contained in ``model`` are mapped back to their unflattened parameters. Parameter keys are not well-defined. For a regular optimizer, the optimizer state_dict contains a mapping from parameter IDs to parameter states. Parameter IDs are the order of parameters in ``optim.param_groups()`` across all the groups. This API also allows user to pass ``optim_input`` for the mapping between parameters and parameter IDs. Using ``optim_input`` is being deprecated. If the optimizer is a ``NamedOptimizer``, the optimizer state_dict does not contain parameter IDs mapping but a mapping from parameter FQNs to parameter states. This API finds the mapping from FQNs to parameters if the optimizer is a ``NamedOptimizer``. If ``use_orig_params`` is True, each rank will have all FSDP-managed parameters but some of these parameters may be empty due to the sharding. For a regular optim.Optimizer, states for those empty parameters will not be initialized. So, when aggregating the FQNs across ranks, no assert will be raised on a rank even if it does not have all the states -- it is valid and FSDP know how to aggregate them. However, FSDP has to ignore handling those parameters that are not managed by FSDP and do not exist on the local rank -- it is managed by other parallelism and FSDP does not know ho to handle/aggregate them. Args: model (nn.Module): Root module (which may or may not be a :class:`FullyShardedDataParallel` instance) whose parameters were passed into the optimizer ``optim``. optim (torch.optim.Optimizer): Optimizer for ``model`` 's parameters. rank0_only (bool): If ``True``, saves the populated :class:`dict` only on rank 0; if ``False``, saves it on all ranks. (Default: ``True``) shard_state (bool): If ``True``, shard and distribute all non-zero-dimension states. Returns: Dict[str, Any]: A :class:`dict` containing the optimizer state for ``model`` 's original unflattened parameters and including keys "state" and "param_groups" following the convention of :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``, then nonzero ranks return an empty :class:`dict`.
20,236
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False
null
20,237
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def with_restore_point_creation_frequency(minutes, func): # Define the key path key_path = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore' # Open the key key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path, 0, winreg.KEY_ALL_ACCESS) # Save the current value try: current_value, _ = winreg.QueryValueEx(key, 'SystemRestorePointCreationFrequency') except FileNotFoundError: current_value = None # Set the new value winreg.SetValueEx(key, 'SystemRestorePointCreationFrequency', 0, winreg.REG_DWORD, minutes) try: # Call the function func() finally: # Restore the original value if current_value is not None: winreg.SetValueEx(key, 'SystemRestorePointCreationFrequency', 0, winreg.REG_DWORD, current_value) else: winreg.DeleteValue(key, 'SystemRestorePointCreationFrequency') # Close the key winreg.CloseKey(key)
null
20,238
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def create_restore_point(name): # Define the command cmd = f'powershell.exe -Command "Checkpoint-Computer -Description \'{name}\' -RestorePointType \'MODIFY_SETTINGS\'"' # Run the command result = subprocess.run(cmd, shell=True) # Check the return code if result.returncode != 0: raise Exception(f'Failed to create restore point. Command returned {result.returncode}')
null
20,239
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def uninstall_msix_package(package_full_name): # Define the PowerShell command cmd = f'powershell.exe -Command "Get-AppxPackage *{package_full_name}* | Remove-AppxPackage"' # Run the command subprocess.run(cmd, shell=True)
null
20,240
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def delete_directory(dir_path): # Check if the directory exists if os.path.exists(dir_path): # Delete the directory shutil.rmtree(dir_path)
null
20,241
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def delete_registry_folders(): try: key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", 0, winreg.KEY_ALL_ACCESS) except WindowsError as e: logging.error(f"Failed to open key: {e}") return i = 0 while True: try: subkey_name = winreg.EnumKey(key, i) if "MicrosoftCorporationII.WindowsSubsystemForAndroid_8wekyb3d8bbwe" in subkey_name: try: winreg.DeleteKeyEx(key, subkey_name) logging.info(f"Deleted key: {subkey_name}") except WindowsError as e: logging.error(f"Failed to delete key {subkey_name}: {e}") i += 1 except WindowsError: # No more subkey to enumerate break winreg.CloseKey(key)
null
20,242
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox target_string = "MicrosoftCorporationII.WindowsSubsystemForAndroid_8wekyb3d8bbwe" def delete_folders_and_files(root_path): target_string = 'MicrosoftCorporationII.WindowsSubsystemForAndroid' # Walk through the file system starting from the root_path for dirpath, dirnames, filenames in os.walk(root_path): # Check each directory for dirname in dirnames: if target_string in dirname: full_dir_path = os.path.join(dirpath, dirname) print(f"Deleting directory: {full_dir_path}") shutil.rmtree(full_dir_path) # Check each file for filename in filenames: if target_string in filename: full_file_path = os.path.join(dirpath, filename) print(f"Deleting file: {full_file_path}") os.remove(full_file_path)
null
20,243
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def delete_shortcuts(target_string, start_menu_dir): # Walk through the file system starting from the start_menu_dir for dirpath, dirnames, filenames in os.walk(start_menu_dir): for filename in filenames: full_file_path = os.path.join(dirpath, filename) target_location = os.path.realpath(full_file_path) if target_string in target_location: print(f"Deleting shortcut: {full_file_path}") os.remove(full_file_path)
null
20,244
import sys import zipfile from pathlib import Path import platform import os from typing import Any, OrderedDict workdir = Path(sys.argv[3]) / "magisk" def extract_as(zip, name, as_name, dir): info = zip.getinfo(name) info.filename = as_name zip.extract(info, workdir / dir)
null
20,245
import html import logging import os import re import sys from pathlib import Path from threading import Thread from typing import Any, OrderedDict from xml.dom import minidom from requests import Session from packaging import version release_type = sys.argv[2] if sys.argv[2] != "" else "Retail" user = '' session = Session() session.verify = False out = session.post( 'https://fe3.delivery.mp.microsoft.com/ClientWebService/client.asmx', data=cookie_content, headers={'Content-Type': 'application/soap+xml; charset=utf-8'} ) doc = minidom.parseString(out.text) out = session.post( 'https://fe3.delivery.mp.microsoft.com/ClientWebService/client.asmx', data=cat_id_content, headers={'Content-Type': 'application/soap+xml; charset=utf-8'} ) doc = minidom.parseString(html.unescape(out.text)) download_files = {} def send_req(i, v, out_file_name): out = session.post( 'https://fe3.delivery.mp.microsoft.com/ClientWebService/client.asmx/secured', data=FE3_file_content.format(user, i, v, release_type), headers={'Content-Type': 'application/soap+xml; charset=utf-8'} ) doc = minidom.parseString(out.text) for l in doc.getElementsByTagName("FileLocation"): url = l.getElementsByTagName("Url")[0].firstChild.nodeValue if len(url) != 99: download_files[out_file_name] = url
null
20,246
from __future__ import annotations from io import TextIOWrapper from typing import OrderedDict from pathlib import Path import sys class Prop(OrderedDict): def __init__(self, file: TextIOWrapper) -> None: super().__init__() for i, line in enumerate(file.read().splitlines(False)): if '=' in line: k, v = line.split('=', 1) self[k] = v else: self[f".{i}"] = line def __str__(self) -> str: return '\n'.join([v if k.startswith('.') else f"{k}={v}" for k, v in self.items()]) def __iadd__(self, other: str) -> Prop: self[f".{len(self)}"] = other return self new_props = { ("product", "brand"): "google", ("system", "brand"): "google", ("product", "manufacturer"): "Google", ("system", "manufacturer"): "Google", ("build", "product"): sys.argv[2], ("product", "name"): sys.argv[2], ("system", "name"): sys.argv[2], ("product", "device"): sys.argv[2], ("system", "device"): sys.argv[2], ("product", "model"): sys.argv[3], ("system", "model"): sys.argv[3], ("build", "flavor"): sys.argv[2] + "-user" } def description(sec: str, p: Prop) -> str: return f"{p[f'ro.{sec}.build.flavor']} {p[f'ro.{sec}.build.version.release_or_codename']} {p[f'ro.{sec}.build.id']} {p[f'ro.{sec}.build.version.incremental']} {p[f'ro.{sec}.build.tags']}" def fingerprint(sec: str, p: Prop) -> str: return f"""{p[f"ro.product.{sec}.brand"]}/{p[f"ro.product.{sec}.name"]}/{p[f"ro.product.{sec}.device"]}:{p[f"ro.{sec}.build.version.release"]}/{p[f"ro.{sec}.build.id"]}/{p[f"ro.{sec}.build.version.incremental"]}:{p[f"ro.{sec}.build.type"]}/{p[f"ro.{sec}.build.tags"]}""" def fix_prop(sec, prop): if not Path(prop).is_file(): return print(f"fixing {prop}", flush=True) with open(prop, 'r') as f: p = Prop(f) p += "# extra props added by MagiskOnWSA" for k, v in new_props.items(): p[f"ro.{k[0]}.{k[1]}"] = v if k[0] == "build": p[f"ro.{sec}.{k[0]}.{k[1]}"] = v elif k[0] == "product": p[f"ro.{k[0]}.{sec}.{k[1]}"] = v p["ro.build.description"] = description(sec, p) p[f"ro.build.fingerprint"] = fingerprint(sec, p) p[f"ro.{sec}.build.description"] = description(sec, p) p[f"ro.{sec}.build.fingerprint"] = fingerprint(sec, p) p[f"ro.bootimage.build.fingerprint"] = fingerprint(sec, p) with open(prop, 'w') as f: f.write(str(p))
null
20,247
from argparse import Namespace from pathlib import Path from typing import Tuple from exegol.config.ConstantConfig import ConstantConfig from exegol.config.DataCache import DataCache from exegol.config.UserConfig import UserConfig from exegol.manager.UpdateManager import UpdateManager from exegol.utils.DockerUtils import DockerUtils def ContainerCompleter(prefix: str, parsed_args: Namespace, **kwargs) -> Tuple[str, ...]: """Function to dynamically load a container list for CLI autocompletion purpose""" data = [c.name for c in DockerUtils.listContainers()] for obj in data: # filter data if needed if prefix and not obj.lower().startswith(prefix.lower()): data.remove(obj) return tuple(data) def ImageCompleter(prefix: str, parsed_args: Namespace, **kwargs) -> Tuple[str, ...]: """Function to dynamically load an image list for CLI autocompletion purpose""" # Skip image completer when container hasn't been selected first (because parameters are all optional, parameters order is not working) if parsed_args is not None and str(parsed_args.action) == "start" and parsed_args.containertag is None: return () try: if parsed_args is not None and str(parsed_args.action) == "install": data = [img_cache.name for img_cache in DataCache().get_images_data().data if img_cache.source == "remote"] else: data = [img_cache.name for img_cache in DataCache().get_images_data().data] except Exception as e: data = [] if len(data) == 0: # Fallback with default data if the cache is not initialized yet data = ["full", "nightly", "ad", "web", "light", "osint"] for obj in data: # filter data if needed if prefix and not obj.lower().startswith(prefix.lower()): data.remove(obj) return tuple(data) The provided code snippet includes necessary dependencies for implementing the `HybridContainerImageCompleter` function. Write a Python function `def HybridContainerImageCompleter(prefix: str, parsed_args: Namespace, **kwargs) -> Tuple[str, ...]` to solve the following problem: Hybrid completer for auto-complet. The selector on exec action is hybrid between image and container depending on the mode (tmp or not). This completer will supply the adequate data. Here is the function: def HybridContainerImageCompleter(prefix: str, parsed_args: Namespace, **kwargs) -> Tuple[str, ...]: """Hybrid completer for auto-complet. The selector on exec action is hybrid between image and container depending on the mode (tmp or not). This completer will supply the adequate data.""" # "exec" parameter is filled first before the selector argument # If "selector" is null but the selector parameter is set in the first exec slot, no longer need to supply completer options if parsed_args.selector is None and parsed_args.exec is not None and len(parsed_args.exec) > 0: return () # In "tmp" mode, the user must choose an image, otherwise it's a container if parsed_args.tmp: return ImageCompleter(prefix, parsed_args, **kwargs) else: return ContainerCompleter(prefix, parsed_args, **kwargs)
Hybrid completer for auto-complet. The selector on exec action is hybrid between image and container depending on the mode (tmp or not). This completer will supply the adequate data.
20,248
from argparse import Namespace from pathlib import Path from typing import Tuple from exegol.config.ConstantConfig import ConstantConfig from exegol.config.DataCache import DataCache from exegol.config.UserConfig import UserConfig from exegol.manager.UpdateManager import UpdateManager from exegol.utils.DockerUtils import DockerUtils class ConstantConfig: """Constant parameters information""" # Exegol Version version: str = "4.3.1" # Exegol documentation link documentation: str = "https://exegol.rtfd.io/" discord: str = "https://discord.gg/cXThyp7D6P" # OS Dir full root path of exegol project src_root_path_obj: Path = Path(__file__).parent.parent.parent.resolve() # Path of the Dockerfile build_context_path_obj: Path build_context_path: str # Path of the entrypoint.sh entrypoint_context_path_obj: Path # Path of the spawn.sh spawn_context_path_obj: Path # Exegol config directory exegol_config_path: Path = Path().home() / ".exegol" # Docker Desktop for mac config file docker_desktop_mac_config_path = Path().home() / "Library/Group Containers/group.com.docker/settings.json" docker_desktop_windows_config_path = Path().home() / "AppData/Roaming/Docker/settings.json" # Install mode, check if Exegol has been git cloned or installed using pip package git_source_installation: bool = (src_root_path_obj / '.git').is_dir() pip_installed: bool = src_root_path_obj.name == "site-packages" # Dockerhub Exegol images repository DOCKER_HUB: str = "hub.docker.com" # Don't handle docker login operations DOCKER_REGISTRY: str = "registry-1.docker.io" # Don't handle docker login operations IMAGE_NAME: str = "nwodtuhs/exegol" GITHUB_REPO: str = "ThePorgs/Exegol" # Docker volume names (no docker volume used at this moment) # Resources repository EXEGOL_RESOURCES_REPO: str = "https://github.com/ThePorgs/Exegol-resources.git" def findResourceContextPath(cls, resource_folder: str, source_path: str) -> Path: """Find the right path to the resources context from Exegol package. Support source clone installation and pip package (venv / user / global context)""" local_src = cls.src_root_path_obj / source_path if local_src.is_dir() or local_src.is_file(): # If exegol is clone from GitHub, build context is accessible from root src return local_src else: # If install from pip if site.ENABLE_USER_SITE: # Detect a user based python env possible_locations = [Path(site.getuserbase())] # Detect a global installed package for loc in site.getsitepackages(): possible_locations.append(Path(loc).parent.parent.parent) # Find a good match for test in possible_locations: context_path = test / resource_folder if context_path.is_dir(): return context_path # Detect a venv context return Path(site.PREFIXES[0]) / resource_folder ConstantConfig.build_context_path_obj = ConstantConfig.findResourceContextPath("exegol-docker-build", "exegol-docker-build") ConstantConfig.build_context_path = str(ConstantConfig.build_context_path_obj) ConstantConfig.entrypoint_context_path_obj = ConstantConfig.findResourceContextPath("exegol-imgsync", "exegol/utils/imgsync/entrypoint.sh") ConstantConfig.spawn_context_path_obj = ConstantConfig.findResourceContextPath("exegol-imgsync", "exegol/utils/imgsync/spawn.sh") class UpdateManager: """Procedure class for updating the exegol tool and docker images""" def updateImage(cls, tag: Optional[str] = None, install_mode: bool = False) -> Optional[ExegolImage]: """User procedure to build/pull docker image""" # List Images image_args = ParametersManager().imagetag # Select image if image_args is not None and tag is None: tag = image_args if tag is None: # Filter for updatable images if install_mode: available_images = [i for i in DockerUtils.listImages() if not i.isLocked()] else: available_images = [i for i in DockerUtils.listImages() if i.isInstall() and not i.isUpToDate() and not i.isLocked()] if len(available_images) == 0: logger.success("All images already installed are up to date!") return None try: # Interactive selection selected_image = ExegolTUI.selectFromTable(available_images, object_type=ExegolImage, allow_None=install_mode) except IndexError: # No images are available if install_mode: # If no image are available in install mode, # either the user does not have internet, # or the image repository has been changed and no docker image is available logger.critical("Exegol can't be installed offline") return None else: try: # Find image by name selected_image = DockerUtils.getImage(tag) except ObjectNotFound: # If the image do not exist, ask to build it if install_mode: return cls.__askToBuild(tag) else: logger.error(f"Image '{tag}' was not found. If you wanted to build a local image, you can use the 'install' action instead.") return None if selected_image is not None and type(selected_image) is ExegolImage: # Update existing ExegolImage if DockerUtils.downloadImage(selected_image, install_mode): sync_result = None # Name comparison allow detecting images without version tag if not selected_image.isVersionSpecific() and selected_image.getName() != selected_image.getLatestVersionName(): with console.status(f"Synchronizing version tag information. Please wait.", spinner_style="blue"): # Download associated version tag. sync_result = DockerUtils.downloadVersionTag(selected_image) # Detect if an error have been triggered during the download if type(sync_result) is str: logger.error(f"Error while downloading version tag, {sync_result}") sync_result = None # if version tag have been successfully download, returning ExegolImage from docker response if sync_result is not None and type(sync_result) is ExegolImage: return sync_result return DockerUtils.getInstalledImage(selected_image.getName()) elif type(selected_image) is str: # Build a new image using TUI selected name, confirmation has already been requested by TUI return cls.buildAndLoad(selected_image) else: # Unknown use case logger.critical(f"Unknown selected image type: {type(selected_image)}. Exiting.") return cast(Optional[ExegolImage], selected_image) def __askToBuild(cls, tag: str) -> Optional[ExegolImage]: """Build confirmation process and image building""" # Need confirmation from the user before starting building. if ParametersManager().build_profile is not None or ParametersManager().build_path is not None or \ Confirm("Do you want to build locally a custom image?", default=False): return cls.buildAndLoad(tag) return None def updateWrapper(cls) -> bool: """Update wrapper source code from git""" result = cls.__updateGit(ExegolModules().getWrapperGit()) if result: cls.__untagUpdateAvailable() logger.empty_line() logger.warning("After this wrapper update, remember to update Exegol [bold]requirements[bold]! ([magenta]python3 -m pip install --upgrade -r requirements.txt[/magenta])") logger.empty_line() return result def updateImageSource(cls) -> bool: """Update image source code from git submodule""" return cls.__updateGit(ExegolModules().getSourceGit()) def updateResources(cls) -> bool: """Update Exegol-resources from git (submodule)""" try: if not ExegolModules().isExegolResourcesReady() and not Confirm('Do you want to update exegol resources.', default=True): return False return cls.__updateGit(ExegolModules().getResourcesGit()) except CancelOperation: # Error during installation, skipping operation return False def __updateGit(gitUtils: GitUtils) -> bool: """User procedure to update local git repository""" if ParametersManager().offline_mode: logger.error("It's not possible to update a repository in offline mode ...") return False if not gitUtils.isAvailable: logger.empty_line() return False logger.info(f"Updating Exegol [green]{gitUtils.getName()}[/green] {gitUtils.getSubject()}") # Check if pending change -> cancel if not gitUtils.safeCheck(): logger.error("Aborting git update.") logger.empty_line() return False current_branch = gitUtils.getCurrentBranch() if current_branch is None: logger.warning("HEAD is detached. Please checkout to an existing branch.") current_branch = "unknown" if logger.isEnabledFor(ExeLog.VERBOSE): available_branches = gitUtils.listBranch() # Ask to checkout only if there is more than one branch available if len(available_branches) > 1: logger.info(f"Current git branch : {current_branch}") # List & Select git branch if current_branch == 'unknown' or current_branch not in available_branches: if "main" in available_branches: default_choice = "main" elif "master" in available_branches: default_choice = "master" else: default_choice = None else: default_choice = current_branch selected_branch = cast(str, ExegolTUI.selectFromList(gitUtils.listBranch(), subject="a git branch", title="[not italic]:palm_tree: [/not italic][gold3]Branch[gold3]", default=default_choice)) elif len(available_branches) == 0: logger.warning("No branch were detected!") selected_branch = None else: # Automatically select the only branch in case of HEAD detachment selected_branch = available_branches[0] # Checkout new branch if selected_branch is not None and selected_branch != current_branch: gitUtils.checkout(selected_branch) # git pull return gitUtils.update() def checkForWrapperUpdate(cls) -> bool: """Check if there is an exegol wrapper update available. Return true if an update is available.""" logger.debug(f"Last wrapper update check: {DataCache().get_wrapper_data().metadata.get_last_check_text()}") # Skipping update check if DataCache().get_wrapper_data().metadata.is_outdated() and not ParametersManager().offline_mode: logger.debug("Running update check") return cls.__checkUpdate() return False def __checkUpdate(cls) -> bool: """Depending on the current version (dev or latest) the method used to find the latest version is not the same. For the stable version, the latest version is fetch from GitHub release. In dev mode, git is used to find if there is some update available.""" isUpToDate = True remote_version = "" current_version = ConstantConfig.version with console.status("Checking for wrapper update. Please wait.", spinner_style="blue"): if re.search(r'[a-z]', ConstantConfig.version, re.IGNORECASE): # Dev version have a letter in the version code and must check updates via git logger.debug("Checking update using: dev mode") module = ExegolModules().getWrapperGit(fast_load=True) if module.isAvailable: isUpToDate = module.isUpToDate() last_commit = module.get_latest_commit() remote_version = "?" if last_commit is None else str(last_commit)[:8] current_version = str(module.get_current_commit())[:8] else: # If Exegol have not been installed from git clone. Auto-check update in this case is only available from mates release logger.verbose("Auto-update checking is not available in the current context") else: # If there is no letter, it's a stable release, and we can compare faster with the latest git tag logger.debug("Checking update using: stable mode") try: remote_version = WebUtils.getLatestWrapperRelease() # On some edge case, remote_version might be None if there is problem if remote_version is None: raise CancelOperation isUpToDate = cls.__compareVersion(remote_version) except CancelOperation: # No internet, postpone update check return False if not isUpToDate: cls.__tagUpdateAvailable(remote_version, current_version) cls.__updateLastCheckTimestamp() return not isUpToDate def __updateLastCheckTimestamp(cls): """Update the last_check metadata timestamp with the current date to avoid multiple update checks.""" DataCache().get_wrapper_data().metadata.update_last_check() DataCache().save_updates() def __compareVersion(cls, version) -> bool: """Compare a remote version with the current one to check if a new release is available.""" isUpToDate = True try: for i in range(len(version.split('.'))): remote = int(version.split('.')[i]) local = int(ConstantConfig.version.split('.')[i]) if remote > local: isUpToDate = False break except ValueError: logger.warning(f'Unable to parse Exegol version : {version} / {ConstantConfig.version}') return isUpToDate def __get_current_version(cls): """Get the current version of the exegol wrapper. Handle dev version and release stable version depending on the current version.""" current_version = ConstantConfig.version if re.search(r'[a-z]', ConstantConfig.version, re.IGNORECASE): module = ExegolModules().getWrapperGit(fast_load=True) if module.isAvailable: current_version = str(module.get_current_commit())[:8] return current_version def display_current_version(): """Get the current version of the exegol wrapper. Handle dev version and release stable version depending on the current version.""" commit_version = "" if re.search(r'[a-z]', ConstantConfig.version, re.IGNORECASE): module = ExegolModules().getWrapperGit(fast_load=True) if module.isAvailable: commit_version = f" [bright_black]\\[{str(module.get_current_commit())[:8]}][/bright_black]" return f"[blue]v{ConstantConfig.version}[/blue]{commit_version}" def __tagUpdateAvailable(cls, latest_version, current_version=None): """Update the 'update available' cache data.""" DataCache().get_wrapper_data().last_version = latest_version DataCache().get_wrapper_data().current_version = cls.__get_current_version() if current_version is None else current_version def isUpdateTag(cls) -> bool: """Check if the cache file is present to announce an available update of the exegol wrapper.""" current_version = cls.__get_current_version() wrapper_data = DataCache().get_wrapper_data() # Check if a latest version exist and if the current version is the same, no external update had occurred if wrapper_data.last_version != current_version and wrapper_data.current_version == current_version: return True else: # If the version changed, exegol have been updated externally (via pip for example) if wrapper_data.current_version != current_version: cls.__untagUpdateAvailable(current_version) return False def display_latest_version(cls) -> str: last_version = DataCache().get_wrapper_data().last_version if len(last_version) == 8 and '.' not in last_version: return f"[bright_black]\\[{last_version}][/bright_black]" return f"[blue]v{last_version}[/blue]" def __untagUpdateAvailable(cls, current_version: Optional[str] = None): """Reset the latest version to the current version""" if current_version is None: current_version = cls.__get_current_version() DataCache().get_wrapper_data().last_version = current_version DataCache().get_wrapper_data().current_version = current_version DataCache().save_updates() def __buildSource(cls, build_name: Optional[str] = None) -> str: """build user process : Ask user is he want to update the git source (to get new& updated build profiles), User choice a build name (if not supplied) User select the path to the dockerfiles (only from CLI parameter) User select a build profile Start docker image building Return the name of the built image""" # Don't force update source if using a custom build_path if ParametersManager().build_path is None: # Ask to update git try: if ExegolModules().getSourceGit().isAvailable and not ExegolModules().getSourceGit().isUpToDate() and \ Confirm("Do you want to update image sources (in order to update local build profiles)?", default=True): cls.updateImageSource() except AssertionError: # Catch None git object assertions logger.warning("Git update is [orange3]not available[/orange3]. Skipping.") # Choose tag name blacklisted_build_name = ["stable", "full"] while build_name is None or build_name in blacklisted_build_name: if build_name is not None: logger.error("This name is reserved and cannot be used for local build. Please choose another one.") build_name = Prompt.ask("[bold blue][?][/bold blue] Choice a name for your build", default="local") # Choose dockerfiles path # Selecting the default path build_path = ConstantConfig.build_context_path_obj if ParametersManager().build_path is not None: custom_build_path = Path(ParametersManager().build_path).expanduser().absolute() # Check if we have a directory or a file to select the project directory if not custom_build_path.is_dir(): custom_build_path = custom_build_path.parent # Check if there is Dockerfile profiles if (custom_build_path / "Dockerfile").is_file() or len(list(custom_build_path.glob("*.dockerfile"))) > 0: # There is at least one Dockerfile build_path = custom_build_path else: logger.critical(f"The directory {custom_build_path.absolute()} doesn't contain any Dockerfile profile.") logger.debug(f"Using {build_path} as path for dockerfiles") # Choose dockerfile profiles = cls.listBuildProfiles(profiles_path=build_path) build_profile: Optional[str] = ParametersManager().build_profile build_dockerfile: Optional[str] = None if build_profile is not None: build_dockerfile = profiles.get(build_profile) if build_dockerfile is None: logger.error(f"Build profile {build_profile} not found.") if build_dockerfile is None: build_profile, build_dockerfile = cast(Tuple[str, str], ExegolTUI.selectFromList(profiles, subject="a build profile", title="[not italic]:dog: [/not italic][gold3]Profile[/gold3]")) logger.debug(f"Using {build_profile} build profile ({build_dockerfile})") # Docker Build DockerUtils.buildImage(tag=build_name, build_profile=build_profile, build_dockerfile=build_dockerfile, dockerfile_path=build_path.as_posix()) return build_name def buildAndLoad(cls, tag: str): """Build an image and load it""" build_name = cls.__buildSource(tag) return DockerUtils.getInstalledImage(build_name) def listBuildProfiles(cls, profiles_path: Path = ConstantConfig.build_context_path_obj) -> Dict: """List every build profiles available locally Return a dict of options {"key = profile name": "value = dockerfile full name"}""" # Default stable profile profiles = {} if (profiles_path / "Dockerfile").is_file(): profiles["full"] = "Dockerfile" # List file *.dockerfile is the build context directory logger.debug(f"Loading build profile from {profiles_path}") docker_files = list(profiles_path.glob("*.dockerfile")) for file in docker_files: # Convert every file to the dict format filename = file.name profile_name = filename.replace(".dockerfile", "") profiles[profile_name] = filename logger.debug(f"List docker build profiles : {profiles}") return profiles def listGitStatus(cls) -> Sequence[Dict[str, str]]: """Get status of every git modules""" result = [] gits = [ExegolModules().getWrapperGit(fast_load=True), ExegolModules().getSourceGit(fast_load=True), ExegolModules().getResourcesGit(fast_load=True, skip_install=True)] with console.status(f"Loading module information", spinner_style="blue") as s: for git in gits: s.update(status=f"Loading module [green]{git.getName()}[/green] information") status = "[bright_black]Unknown[/bright_black]" if ParametersManager().offline_mode else git.getTextStatus() branch = git.getCurrentBranch() if branch is None: if "not supported" in status: branch = "[bright_black]N/A[/bright_black]" else: branch = "[bright_black][g]? :person_shrugging:[/g][/bright_black]" result.append({"name": git.getName().capitalize(), "status": status, "current branch": branch}) return result The provided code snippet includes necessary dependencies for implementing the `BuildProfileCompleter` function. Write a Python function `def BuildProfileCompleter(prefix: str, parsed_args: Namespace, **kwargs) -> Tuple[str, ...]` to solve the following problem: Completer function for build profile parameter. The completer must be trigger only when an image name have already been chosen. Here is the function: def BuildProfileCompleter(prefix: str, parsed_args: Namespace, **kwargs) -> Tuple[str, ...]: """Completer function for build profile parameter. The completer must be trigger only when an image name have already been chosen.""" # The build profile completer must be trigger only when an image name have been set by user if parsed_args is not None and parsed_args.imagetag is None: return () # Default build path build_path = ConstantConfig.build_context_path_obj # Handle custom build path if parsed_args is not None and parsed_args.build_path is not None: custom_build_path = Path(parsed_args.build_path).expanduser().absolute() # Check if we have a directory or a file to select the project directory if not custom_build_path.is_dir(): custom_build_path = custom_build_path.parent build_path = custom_build_path # Find profile list data = list(UpdateManager.listBuildProfiles(profiles_path=build_path).keys()) for obj in data: if prefix and not obj.lower().startswith(prefix.lower()): data.remove(obj) return tuple(data)
Completer function for build profile parameter. The completer must be trigger only when an image name have already been chosen.
20,249
from argparse import Namespace from pathlib import Path from typing import Tuple from exegol.config.ConstantConfig import ConstantConfig from exegol.config.DataCache import DataCache from exegol.config.UserConfig import UserConfig from exegol.manager.UpdateManager import UpdateManager from exegol.utils.DockerUtils import DockerUtils class UserConfig(DataFileUtils, metaclass=MetaSingleton): """This class allows loading user defined configurations""" # Static choices start_shell_options = {'zsh', 'bash', 'tmux'} shell_logging_method_options = {'script', 'asciinema'} desktop_available_proto = {'http', 'vnc'} def __init__(self): # Defaults User config self.private_volume_path: Path = ConstantConfig.exegol_config_path / "workspaces" self.my_resources_path: Path = ConstantConfig.exegol_config_path / "my-resources" self.exegol_resources_path: Path = self.__default_resource_location('exegol-resources') self.auto_check_updates: bool = True self.auto_remove_images: bool = True self.auto_update_workspace_fs: bool = False self.default_start_shell: str = "zsh" self.shell_logging_method: str = "asciinema" self.shell_logging_compress: bool = True self.desktop_default_enable: bool = False self.desktop_default_localhost: bool = True self.desktop_default_proto: str = "http" super().__init__("config.yml", "yml") def _build_file_content(self): config = f"""# Exegol configuration # Full documentation: https://exegol.readthedocs.io/en/latest/exegol-wrapper/advanced-uses.html#id1 # Volume path can be changed at any time but existing containers will not be affected by the update volumes: # The my-resources volume is a storage space dedicated to the user to customize his environment and tools. This volume can be shared across all exegol containers. # Attention! The permissions of this folder (and subfolders) will be updated to share read/write rights between the host (user) and the container (root). Do not modify this path to a folder on which the permissions (chmod) should not be modified. my_resources_path: {self.my_resources_path} # Exegol resources are data and static tools downloaded in addition to docker images. These tools are complementary and are accessible directly from the host. exegol_resources_path: {self.exegol_resources_path} # When containers do not have an explicitly declared workspace, a dedicated folder will be created at this location to share the workspace with the host but also to save the data after deleting the container private_workspace_path: {self.private_volume_path} config: # Enables automatic check for wrapper updates auto_check_update: {self.auto_check_updates} # Automatically remove outdated image when they are no longer used auto_remove_image: {self.auto_remove_images} # Automatically modifies the permissions of folders and sub-folders in your workspace by default to enable file sharing between the container with your host user. auto_update_workspace_fs: {self.auto_update_workspace_fs} # Default shell command to start default_start_shell: {self.default_start_shell} # Change the configuration of the shell logging functionality shell_logging: #Choice of the method used to record the sessions (script or asciinema) logging_method: {self.shell_logging_method} # Enable automatic compression of log files (with gzip) enable_log_compression: {self.shell_logging_compress} # Configure your Exegol Desktop desktop: # Enables or not the desktop mode by default # If this attribute is set to True, then using the CLI --desktop option will be inverted and will DISABLE the feature enabled_by_default: {self.desktop_default_enable} # Default desktop protocol,can be "http", or "vnc" (additional protocols to come in the future, check online documentation for updates). default_protocol: {self.desktop_default_proto} # Desktop service is exposed on localhost by default. If set to true, services will be exposed on localhost (127.0.0.1) otherwise it will be exposed on 0.0.0.0. This setting can be overwritten with --desktop-config localhost_by_default: {self.desktop_default_localhost} """ # TODO handle default image selection # TODO handle default start container return config def __default_resource_location(folder_name: str) -> Path: local_src = ConstantConfig.src_root_path_obj / folder_name if local_src.is_dir(): # If exegol is clone from github, exegol-resources submodule is accessible from root src return local_src else: # Default path for pip installation return ConstantConfig.exegol_config_path / folder_name def _process_data(self): # Volume section volumes_data = self._raw_data.get("volumes", {}) # Catch existing but empty section if volumes_data is None: volumes_data = {} self.my_resources_path = self._load_config_path(volumes_data, 'my_resources_path', self.my_resources_path) self.private_volume_path = self._load_config_path(volumes_data, 'private_workspace_path', self.private_volume_path) self.exegol_resources_path = self._load_config_path(volumes_data, 'exegol_resources_path', self.exegol_resources_path) # Config section config_data = self._raw_data.get("config", {}) # Catch existing but empty section if config_data is None: config_data = {} self.auto_check_updates = self._load_config_bool(config_data, 'auto_check_update', self.auto_check_updates) self.auto_remove_images = self._load_config_bool(config_data, 'auto_remove_image', self.auto_remove_images) self.auto_update_workspace_fs = self._load_config_bool(config_data, 'auto_update_workspace_fs', self.auto_update_workspace_fs) self.default_start_shell = self._load_config_str(config_data, 'default_start_shell', self.default_start_shell, choices=self.start_shell_options) # Shell_logging section shell_logging_data = config_data.get("shell_logging", {}) self.shell_logging_method = self._load_config_str(shell_logging_data, 'logging_method', self.shell_logging_method, choices=self.shell_logging_method_options) self.shell_logging_compress = self._load_config_bool(shell_logging_data, 'enable_log_compression', self.shell_logging_compress) # Desktop section desktop_data = config_data.get("desktop", {}) self.desktop_default_enable = self._load_config_bool(desktop_data, 'enabled_by_default', self.desktop_default_enable) self.desktop_default_proto = self._load_config_str(desktop_data, 'default_proto', self.desktop_default_proto, choices=self.desktop_available_proto) self.desktop_default_localhost = self._load_config_bool(desktop_data, 'localhost_by_default', self.desktop_default_localhost) def get_configs(self) -> List[str]: """User configs getter each options""" configs = [ f"User config file: [magenta]{self._file_path}[/magenta]", f"Private workspace: [magenta]{self.private_volume_path}[/magenta]", f"Exegol resources: [magenta]{self.exegol_resources_path}[/magenta]", f"My resources: [magenta]{self.my_resources_path}[/magenta]", f"Auto-check updates: {boolFormatter(self.auto_check_updates)}", f"Auto-remove images: {boolFormatter(self.auto_remove_images)}", f"Auto-update fs: {boolFormatter(self.auto_update_workspace_fs)}", f"Default start shell: [blue]{self.default_start_shell}[/blue]", f"Shell logging method: [blue]{self.shell_logging_method}[/blue]", f"Shell logging compression: {boolFormatter(self.shell_logging_compress)}", f"Desktop enabled by default: {boolFormatter(self.desktop_default_enable)}", f"Desktop default protocol: [blue]{self.desktop_default_proto}[/blue]", f"Desktop default host: [blue]{'localhost' if self.desktop_default_localhost else '0.0.0.0'}[/blue]", ] # TUI can't be called from here to avoid circular importation return configs def DesktopConfigCompleter(prefix: str, **kwargs) -> Tuple[str, ...]: options = list(UserConfig.desktop_available_proto) for obj in options: if prefix and not obj.lower().startswith(prefix.lower()): options.remove(obj) # TODO add interface enum return tuple(options)
null
20,250
from argparse import Namespace from pathlib import Path from typing import Tuple from exegol.config.ConstantConfig import ConstantConfig from exegol.config.DataCache import DataCache from exegol.config.UserConfig import UserConfig from exegol.manager.UpdateManager import UpdateManager from exegol.utils.DockerUtils import DockerUtils The provided code snippet includes necessary dependencies for implementing the `VoidCompleter` function. Write a Python function `def VoidCompleter(**kwargs) -> Tuple` to solve the following problem: No option to auto-complet Here is the function: def VoidCompleter(**kwargs) -> Tuple: """No option to auto-complet""" return ()
No option to auto-complet
20,251
import re from typing import Tuple, Union The provided code snippet includes necessary dependencies for implementing the `boolFormatter` function. Write a Python function `def boolFormatter(val: bool) -> str` to solve the following problem: Generic text formatter for bool value Here is the function: def boolFormatter(val: bool) -> str: """Generic text formatter for bool value""" return '[green]On :heavy_check_mark:[/green] ' if val else '[orange3]Off :axe:[/orange3]'
Generic text formatter for bool value
20,252
import re from typing import Tuple, Union The provided code snippet includes necessary dependencies for implementing the `getColor` function. Write a Python function `def getColor(val: Union[bool, int, str]) -> Tuple[str, str]` to solve the following problem: Generic text color getter for bool value Here is the function: def getColor(val: Union[bool, int, str]) -> Tuple[str, str]: """Generic text color getter for bool value""" if type(val) is str: try: val = int(val) except ValueError: val = False return ('[green]', '[/green]') if val else ('[orange3]', '[/orange3]')
Generic text color getter for bool value
20,253
import re from typing import Tuple, Union The provided code snippet includes necessary dependencies for implementing the `richLen` function. Write a Python function `def richLen(text: str) -> int` to solve the following problem: Get real length of a text without Rich colors Here is the function: def richLen(text: str) -> int: """Get real length of a text without Rich colors""" # remove rich color tags color_removed = re.sub(r"\[/?[^]]+]", '', text, 0, re.MULTILINE) # replace emoji by two random char (because emoji are wide) emoji_removed = re.sub(r":[a-z-_+()\d'’.&]+:", 'XX', color_removed, 0, re.MULTILINE) return len(emoji_removed)
Get real length of a text without Rich colors
20,254
import re from typing import Tuple, Union def getArchColor(arch: str) -> str: if arch.startswith("arm"): color = "slate_blue3" elif "amd64" == arch: color = "medium_orchid3" else: color = "yellow3" return color
null
20,255
import rich.prompt The provided code snippet includes necessary dependencies for implementing the `Confirm` function. Write a Python function `def Confirm(question: str, default: bool) -> bool` to solve the following problem: Quick function to format rich Confirmation and options on every exegol interaction Here is the function: def Confirm(question: str, default: bool) -> bool: """Quick function to format rich Confirmation and options on every exegol interaction""" default_text = "[bright_magenta][Y/n][/bright_magenta]" if default else "[bright_magenta]\\[y/N][/bright_magenta]" formatted_question = f"[bold blue][?][/bold blue] {question} {default_text}" return rich.prompt.Confirm.ask( formatted_question, show_choices=False, show_default=False, default=default)
Quick function to format rich Confirmation and options on every exegol interaction
20,256
from typing import Union, Optional, Dict from git import RemoteProgress from git.objects.submodule.base import UpdateProgress from rich.console import Console from rich.progress import Progress, ProgressColumn, GetTimeCallable, Task from exegol.utils.ExeLog import console as exelog_console from exegol.utils.ExeLog import logger from exegol.utils.MetaSingleton import MetaSingleton class MetaGitProgress(Progress, metaclass=MetaSingleton): def __init__(self, *columns: Union[str, ProgressColumn], console: Optional[Console] = None, auto_refresh: bool = True, refresh_per_second: float = 10, speed_estimate_period: float = 30.0, transient: bool = False, redirect_stdout: bool = True, redirect_stderr: bool = True, get_time: Optional[GetTimeCallable] = None, disable: bool = False, expand: bool = False) -> None: def handle_task(op_code: int, ref_op_code: int, description: str, total: int, completed: int, message: str = '') -> bool: logger: ExeLog = cast(ExeLog, logging.getLogger("main")) logger.setLevel(logging.INFO) def clone_update_progress(op_code: int, cur_count: Union[str, float], max_count: Union[str, float, None] = None, message: str = '') -> None: # Full debug log # logger.debug(f"[{op_code}] {cur_count}/{max_count} : '{message}'") if max_count is None: max_count = 0 max_count = int(max_count) cur_count = int(cur_count) main_task = MetaGitProgress().tasks[0] step = 0 # COUNTING if MetaGitProgress.handle_task(op_code, RemoteProgress.COUNTING, "Counting git objects", max_count, cur_count, message): step = 1 # COMPRESSING elif MetaGitProgress.handle_task(op_code, RemoteProgress.COMPRESSING, "Compressing", max_count, cur_count, message): step = 2 # RECEIVING elif MetaGitProgress.handle_task(op_code, RemoteProgress.RECEIVING, "Downloading", max_count, cur_count, message): step = 3 # RESOLVING elif MetaGitProgress.handle_task(op_code, RemoteProgress.RESOLVING, "Resolving", max_count, cur_count, message): step = 4 else: logger.debug(f"Git OPCODE {op_code} is not handled by Exegol TUI.") main_task.total = 4 main_task.completed = step
null
20,257
logger: ExeLog = cast(ExeLog, logging.getLogger("main")) logger.setLevel(logging.INFO) def print_exception_banner(): logger.error("It seems that something unexpected happened ...") logger.error("To draw our attention to the problem and allow us to fix it, you can share your error with us " "(by [orange3]copying and pasting[/orange3] it with this syntax: ``` <error> ```) " "by creating a GitHub issue at this address: https://github.com/ThePorgs/Exegol/issues") logger.success("Thank you for your collaboration!")
null
20,258
import logging import re import stat import subprocess from pathlib import Path, PurePath from typing import Optional from exegol.config.EnvInfo import EnvInfo from exegol.utils.ExeLog import logger logger: ExeLog = cast(ExeLog, logging.getLogger("main")) logger.setLevel(logging.INFO) The provided code snippet includes necessary dependencies for implementing the `parseDockerVolumePath` function. Write a Python function `def parseDockerVolumePath(source: str) -> PurePath` to solve the following problem: Parse docker volume path to find the corresponding host path. Here is the function: def parseDockerVolumePath(source: str) -> PurePath: """Parse docker volume path to find the corresponding host path.""" # Check if path is from Windows Docker Desktop matches = re.match(r"^/run/desktop/mnt/host/([a-z])(/.*)$", source, re.IGNORECASE) if matches: # Convert Windows Docker-VM style volume path to local OS path src_path = Path(f"{matches.group(1).upper()}:{matches.group(2)}") logger.debug(f"Windows style detected : {src_path}") return src_path else: # Remove docker mount path if exist return PurePath(source.replace('/run/desktop/mnt/host', ''))
Parse docker volume path to find the corresponding host path.
20,259
import logging import re import stat import subprocess from pathlib import Path, PurePath from typing import Optional from exegol.config.EnvInfo import EnvInfo from exegol.utils.ExeLog import logger def resolvPath(path: Path) -> str: """Resolv a filesystem path depending on the environment. On WSL, Windows PATH can be resolved using 'wslpath'.""" if path is None: return '' # From WSL, Windows Path must be resolved (try to detect a Windows path with '\') if EnvInfo.current_platform == "WSL" and '\\' in str(path): try: # Resolv Windows path on WSL environment p = subprocess.Popen(["wslpath", "-a", str(path)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = p.communicate() logger.debug(f"Resolv path input: {path}") logger.debug(f"Resolv path output: {output!r}") if err != b'': # result is returned to STDERR when the translation didn't properly find a match logger.debug(f"Error on FS path resolution: {err!r}. Input path is probably a linux path.") else: return output.decode('utf-8').strip() except FileNotFoundError: logger.warning("Missing WSL tools: 'wslpath'. Skipping resolution.") return str(path) The provided code snippet includes necessary dependencies for implementing the `resolvStrPath` function. Write a Python function `def resolvStrPath(path: Optional[str]) -> str` to solve the following problem: Try to resolv a filesystem path from a string. Here is the function: def resolvStrPath(path: Optional[str]) -> str: """Try to resolv a filesystem path from a string.""" if path is None: return '' return resolvPath(Path(path))
Try to resolv a filesystem path from a string.
20,260
import logging import re import stat import subprocess from pathlib import Path, PurePath from typing import Optional from exegol.config.EnvInfo import EnvInfo from exegol.utils.ExeLog import logger logger: ExeLog = cast(ExeLog, logging.getLogger("main")) logger.setLevel(logging.INFO) The provided code snippet includes necessary dependencies for implementing the `setGidPermission` function. Write a Python function `def setGidPermission(root_folder: Path)` to solve the following problem: Set the setgid permission bit to every recursive directory Here is the function: def setGidPermission(root_folder: Path): """Set the setgid permission bit to every recursive directory""" logger.verbose(f"Updating the permissions of {root_folder} (and sub-folders) to allow file sharing between the container and the host user") logger.debug(f"Adding setgid permission recursively on directories from {root_folder}") perm_alert = False # Set permission to root directory try: root_folder.chmod(root_folder.stat().st_mode | stat.S_IRWXG | stat.S_ISGID) except PermissionError: # Trigger the error only if the permission is not already set if not root_folder.stat().st_mode & stat.S_ISGID: logger.warning(f"The permission of this directory ({root_folder}) cannot be automatically changed.") perm_alert = True for sub_item in root_folder.rglob('*'): # Find every subdirectory try: if not sub_item.is_dir(): continue except PermissionError: if not sub_item.is_symlink(): logger.error(f"Permission denied when trying to resolv {str(sub_item)}") continue # If the permission is already set, skip if sub_item.stat().st_mode & stat.S_ISGID: continue # Set the permission (g+s) to every child directory try: sub_item.chmod(sub_item.stat().st_mode | stat.S_IRWXG | stat.S_ISGID) except PermissionError: logger.warning(f"The permission of this directory ({sub_item}) cannot be automatically changed.") perm_alert = True if perm_alert: logger.warning(f"In order to share files between your host and exegol (without changing the permission), you can run [orange3]manually[/orange3] this command from your [red]host[/red]:") logger.empty_line() logger.raw(f"sudo chgrp -R $(id -g) {root_folder} && sudo find {root_folder} -type d -exec chmod g+rws {{}} \\;", level=logging.WARNING) logger.empty_line() logger.empty_line()
Set the setgid permission bit to every recursive directory
20,261
import numpy as np def convert_to_ndc(origins, directions, ndc_coeffs, near: float = 1.0): """Convert a set of rays to NDC coordinates.""" t = (near - origins[Ellipsis, 2]) / directions[Ellipsis, 2] origins = origins + t[Ellipsis, None] * directions dx, dy, dz = directions[:, 0], directions[:, 1], directions[:, 2] ox, oy, oz = origins[:, 0], origins[:, 1], origins[:, 2] o0 = ndc_coeffs[0] * (ox / oz) o1 = ndc_coeffs[1] * (oy / oz) o2 = 1 - 2 * near / oz d0 = ndc_coeffs[0] * (dx / dz - ox / oz) d1 = ndc_coeffs[1] * (dy / dz - oy / oz) d2 = 2 * near / oz origins = np.stack([o0, o1, o2], -1) directions = np.stack([d0, d1, d2], -1) return origins, directions def batchified_get_rays( intrinsics, extrinsics, image_sizes, use_pixel_centers, get_radii, ndc_coord, ndc_coeffs, multlosses, ): radii = None multloss_expand = None center = 0.5 if use_pixel_centers else 0.0 mesh_grids = [ np.meshgrid( np.arange(w, dtype=np.float32) + center, np.arange(h, dtype=np.float32) + center, indexing="xy", ) for (h, w) in image_sizes ] i_coords = [mesh_grid[0] for mesh_grid in mesh_grids] j_coords = [mesh_grid[1] for mesh_grid in mesh_grids] dirs = [ np.stack( [ (i - intrinsic[0][2]) / intrinsic[0][0], (j - intrinsic[1][2]) / intrinsic[1][1], np.ones_like(i), ], -1, ) for (intrinsic, i, j) in zip(intrinsics, i_coords, j_coords) ] rays_o = np.concatenate( [ np.tile(extrinsic[np.newaxis, :3, 3], (1, h * w, 1)).reshape(-1, 3) for (extrinsic, (h, w)) in zip(extrinsics, image_sizes) ] ).astype(np.float32) rays_d = np.concatenate( [ np.einsum("hwc, rc -> hwr", dir, extrinsic[:3, :3]).reshape(-1, 3) for (dir, extrinsic) in zip(dirs, extrinsics) ] ).astype(np.float32) viewdirs = rays_d viewdirs /= np.linalg.norm(viewdirs, axis=-1, keepdims=True) if ndc_coord: rays_o, rays_d = convert_to_ndc(rays_o, rays_d, ndc_coeffs) if get_radii: if not ndc_coord: rays_d_orig = [ np.einsum("hwc, rc -> hwr", dir, extrinsic[:3, :3]) for (dir, extrinsic) in zip(dirs, extrinsics) ] dx = [ np.sqrt(np.sum((v[:-1, :, :] - v[1:, :, :]) ** 2, -1)) for v in rays_d_orig ] dx = [np.concatenate([v, v[-2:-1, :]], 0) for v in dx] _radii = [v[..., None] * 2 / np.sqrt(12) for v in dx] radii = np.concatenate([radii_each.reshape(-1) for radii_each in _radii])[ ..., None ] else: rays_o_orig, cnt = [], 0 for (h, w) in image_sizes: rays_o_orig.append(rays_o[cnt : cnt + h * w].reshape(h, w, 3)) cnt += h * w dx = [ np.sqrt(np.sum((v[:-1, :, :] - v[1:, :, :]) ** 2, -1)) for v in rays_o_orig ] dx = [np.concatenate([v, v[-2:-1, :]], 0) for v in dx] dy = [ np.sqrt(np.sum((v[:, :-1, :] - v[:, 1:, :]) ** 2, -1)) for v in rays_o_orig ] dy = [np.concatenate([v, v[:, -2:-1]], 1) for v in dy] _radii = [(vx + vy)[..., None] / np.sqrt(12) for (vx, vy) in zip(dx, dy)] radii = np.concatenate([radii_each.reshape(-1) for radii_each in _radii])[ ..., None ] if multlosses is not None: multloss_expand = np.concatenate( [ np.array([scale] * (h * w)) for (scale, (h, w)) in zip(multlosses, image_sizes) ] )[..., None] return rays_o, rays_d, viewdirs, radii, multloss_expand
null
20,262
import numpy as np def pad_poses(p: np.ndarray) -> np.ndarray: """Pad [..., 3, 4] pose matrices with a homogeneous bottom row [0,0,0,1].""" bottom = np.broadcast_to([0, 0, 0, 1.0], p[..., :1, :4].shape) return np.concatenate([p[..., :3, :4], bottom], axis=-2) def unpad_poses(p: np.ndarray) -> np.ndarray: """Remove the homogeneous bottom row from [..., 4, 4] pose matrices.""" return p[..., :3, :4] The provided code snippet includes necessary dependencies for implementing the `transform_poses_pca` function. Write a Python function `def transform_poses_pca(poses: np.ndarray)` to solve the following problem: Transforms poses so principal components lie on XYZ axes. Args: poses: a (N, 3, 4) array containing the cameras' camera to world transforms. Returns: A tuple (poses, transform), with the transformed poses and the applied camera_to_world transforms. Here is the function: def transform_poses_pca(poses: np.ndarray): """Transforms poses so principal components lie on XYZ axes. Args: poses: a (N, 3, 4) array containing the cameras' camera to world transforms. Returns: A tuple (poses, transform), with the transformed poses and the applied camera_to_world transforms. """ t = poses[:, :3, 3] t_mean = t.mean(axis=0) t = t - t_mean eigval, eigvec = np.linalg.eig(t.T @ t) # Sort eigenvectors in order of largest to smallest eigenvalue. inds = np.argsort(eigval)[::-1] eigvec = eigvec[:, inds] rot = eigvec.T if np.linalg.det(rot) < 0: rot = np.diag(np.array([1, 1, -1])) @ rot transform = np.concatenate([rot, rot @ -t_mean[:, None]], -1) poses_recentered = unpad_poses(transform @ pad_poses(poses)) transform = np.concatenate([transform, np.eye(4)[3:]], axis=0) # Flip coordinate system if z component of y-axis is negative if poses_recentered.mean(axis=0)[2, 1] < 0: poses_recentered = np.diag(np.array([1, -1, -1])) @ poses_recentered transform = np.diag(np.array([1, -1, -1, 1])) @ transform # Just make sure it's it in the [-1, 1]^3 cube scale_factor = 1.0 / np.max(np.abs(poses_recentered[:, :3, 3])) poses_recentered[:, :3, 3] *= scale_factor transform = np.diag(np.array([scale_factor] * 3 + [1])) @ transform return poses_recentered, transform
Transforms poses so principal components lie on XYZ axes. Args: poses: a (N, 3, 4) array containing the cameras' camera to world transforms. Returns: A tuple (poses, transform), with the transformed poses and the applied camera_to_world transforms.
20,263
import numpy as np def focus_point_fn(poses: np.ndarray) -> np.ndarray: """Calculate nearest point to all focal axes in poses.""" directions, origins = poses[:, :3, 2:3], poses[:, :3, 3:4] m = np.eye(3) - directions * np.transpose(directions, [0, 2, 1]) mt_m = np.transpose(m, [0, 2, 1]) @ m focus_pt = np.linalg.inv(mt_m.mean(0)) @ (mt_m @ origins).mean(0)[:, 0] return focus_pt def viewmatrix(lookdir: np.ndarray, up: np.ndarray, position: np.ndarray) -> np.ndarray: """Construct lookat view matrix.""" vec2 = normalize(lookdir) vec0 = normalize(np.cross(up, vec2)) vec1 = normalize(np.cross(vec2, vec0)) m = np.stack([vec0, vec1, vec2, position], axis=1) return m The provided code snippet includes necessary dependencies for implementing the `generate_ellipse_path` function. Write a Python function `def generate_ellipse_path( poses: np.ndarray, n_frames: int = 5, const_speed: bool = True, z_variation: float = 0.0, z_phase: float = 0.0, ) -> np.ndarray` to solve the following problem: Generate an elliptical render path based on the given poses. Here is the function: def generate_ellipse_path( poses: np.ndarray, n_frames: int = 5, const_speed: bool = True, z_variation: float = 0.0, z_phase: float = 0.0, ) -> np.ndarray: """Generate an elliptical render path based on the given poses.""" # Calculate the focal point for the path (cameras point toward this). center = focus_point_fn(poses) # Path height sits at z=0 (in middle of zero-mean capture pattern). offset = np.array([center[0], center[1], 0]) # Calculate scaling for ellipse axes based on input camera positions. sc = np.percentile(np.abs(poses[:, :3, 3] - offset), 90, axis=0) # Use ellipse that is symmetric about the focal point in xy. low = -sc + offset high = sc + offset # Optional height variation need not be symmetric z_low = np.percentile((poses[:, :3, 3]), 10, axis=0) z_high = np.percentile((poses[:, :3, 3]), 90, axis=0) def get_positions(theta): # Interpolate between bounds with trig functions to get ellipse in x-y. # Optionally also interpolate in z to change camera height along path. return np.stack( [ low[0] + (high - low)[0] * (np.cos(theta) * 0.5 + 0.5), low[1] + (high - low)[1] * (np.sin(theta) * 0.5 + 0.5), z_variation * ( z_low[2] + (z_high - z_low)[2] * (np.cos(theta + 2 * np.pi * z_phase) * 0.5 + 0.5) ), ], -1, ) theta = np.linspace(0, 2.0 * np.pi, n_frames + 1, endpoint=True) positions = get_positions(theta) # Throw away duplicated last position. positions = positions[:-1] # Set path's up vector to axis closest to average of input pose up vectors. avg_up = poses[:, :3, 1].mean(0) avg_up = avg_up / np.linalg.norm(avg_up) ind_up = np.argmax(np.abs(avg_up)) up = np.eye(3)[ind_up] * np.sign(avg_up[ind_up]) return np.stack([viewmatrix(p - center, up, p) for p in positions])
Generate an elliptical render path based on the given poses.
20,264
import json import os import imageio import numpy as np import torch def pose_spherical(theta, phi, radius): c2w = trans_t(radius) c2w = rot_phi(phi / 180.0 * np.pi) @ c2w c2w = rot_theta(theta / 180.0 * np.pi) @ c2w c2w = ( torch.tensor([[-1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]).float() ) return c2w def load_blender_ms_data( datadir: str, scene_name: str, train_skip: int, val_skip: int, test_skip: int, cam_scale_factor: float, white_bkgd: bool, ): basedir = os.path.join(datadir, scene_name) cam_trans = np.diag(np.array([1, -1, -1, 1], dtype=np.float32)) splits = ["train", "val", "test"] metadatapath = os.path.join(basedir, "metadata.json") with open(metadatapath) as fp: metadata = json.load(fp) images = [] extrinsics = [] counts = [0] focals = [] multlosses = [] for s in splits: meta = metadata[s] imgs = [] poses = [] fs = [] multloss = [] if s == "train": skip = train_skip elif s == "val": skip = val_skip elif s == "test": skip = test_skip for (filepath, pose, focal, mult) in zip( meta["file_path"][::skip], meta["cam2world"][::skip], meta["focal"][::skip], meta["lossmult"][::skip], ): fname = os.path.join(basedir, filepath) imgs.append(imageio.imread(fname)) poses.append(np.array(pose)) fs.append(focal) multloss.append(mult) imgs = [(img / 255.0).astype(np.float32) for img in imgs] poses = np.array(poses).astype(np.float32) counts.append(counts[-1] + len(imgs)) images += imgs focals += fs extrinsics.append(poses) multlosses.append(np.array(multloss)) i_split = [np.arange(counts[i], counts[i + 1]) for i in range(3)] extrinsics = np.concatenate(extrinsics, 0) extrinsics[:, :3, 3] *= cam_scale_factor extrinsics = extrinsics @ cam_trans image_sizes = np.array([img.shape[:2] for img in images]) num_frame = len(extrinsics) i_split += [np.arange(num_frame)] intrinsics = np.array( [ [[focal, 0.0, 0.5 * w], [0.0, focal, 0.5 * h], [0.0, 0.0, 1.0]] for (focal, (h, w)) in zip(focals, image_sizes) ] ) render_poses = torch.stack( [ pose_spherical(angle, -30.0, 4.0) @ cam_trans for angle in np.linspace(-180, 180, 40 + 1)[:-1] ], 0, ) render_poses[:, :3, 3] *= cam_scale_factor near = 2.0 far = 6.0 if white_bkgd: images = [ image[..., :3] * image[..., -1:] + (1.0 - image[..., -1:]) for image in images ] else: images = [image[..., :3] for image in images] multlosses = np.concatenate(multlosses) return ( images, intrinsics, extrinsics, image_sizes, near, far, (-1, -1), i_split, render_poses, multlosses, # Train only )
null
20,265
import json import os import gdown import imageio import numpy as np import torch def pose_spherical(theta, phi, radius): c2w = trans_t(radius) c2w = rot_phi(phi / 180.0 * np.pi) @ c2w c2w = rot_theta(theta / 180.0 * np.pi) @ c2w c2w = ( torch.tensor([[-1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]).float() ) return c2w def load_blender_data( datadir: str, scene_name: str, train_skip: int, val_skip: int, test_skip: int, cam_scale_factor: float, white_bkgd: bool, ): basedir = os.path.join(datadir, scene_name) cam_trans = np.diag(np.array([1, -1, -1, 1], dtype=np.float32)) splits = ["train", "val", "test"] metas = {} for s in splits: with open(os.path.join(basedir, "transforms_{}.json".format(s)), "r") as fp: metas[s] = json.load(fp) images = [] extrinsics = [] counts = [0] for s in splits: meta = metas[s] imgs = [] poses = [] if s == "train": skip = train_skip elif s == "val": skip = val_skip elif s == "test": skip = test_skip for frame in meta["frames"][::skip]: fname = os.path.join(basedir, frame["file_path"] + ".png") imgs.append(imageio.imread(fname)) poses.append(np.array(frame["transform_matrix"])) imgs = (np.array(imgs) / 255.0).astype(np.float32) # keep all 4 channels (RGBA) poses = np.array(poses).astype(np.float32) counts.append(counts[-1] + imgs.shape[0]) images.append(imgs) extrinsics.append(poses) i_split = [np.arange(counts[i], counts[i + 1]) for i in range(3)] images = np.concatenate(images, 0) extrinsics = np.concatenate(extrinsics, 0) extrinsics[:, :3, 3] *= cam_scale_factor extrinsics = extrinsics @ cam_trans h, w = imgs[0].shape[:2] num_frame = len(extrinsics) i_split += [np.arange(num_frame)] camera_angle_x = float(meta["camera_angle_x"]) focal = 0.5 * w / np.tan(0.5 * camera_angle_x) intrinsics = np.array( [ [[focal, 0.0, 0.5 * w], [0.0, focal, 0.5 * h], [0.0, 0.0, 1.0]] for _ in range(num_frame) ] ) image_sizes = np.array([[h, w] for _ in range(num_frame)]) render_poses = torch.stack( [ pose_spherical(angle, -30.0, 4.0) @ cam_trans for angle in np.linspace(-180, 180, 40 + 1)[:-1] ], 0, ) render_poses[:, :3, 3] *= cam_scale_factor near = 2.0 far = 6.0 if white_bkgd: images = images[..., :3] * images[..., -1:] + (1.0 - images[..., -1:]) else: images = images[..., :3] return ( images, intrinsics, extrinsics, image_sizes, near, far, (-1, -1), i_split, render_poses, )
null
20,266
import glob import os from typing import * import imageio import numpy as np def find_files(dir, exts): if os.path.isdir(dir): files_grabbed = [] for ext in exts: files_grabbed.extend(glob.glob(os.path.join(dir, ext))) if len(files_grabbed) > 0: files_grabbed = sorted(files_grabbed) return files_grabbed else: return [] def similarity_from_cameras(c2w): """ Get a similarity transform to normalize dataset from c2w (OpenCV convention) cameras :param c2w: (N, 4) :return T (4,4) , scale (float) """ t = c2w[:, :3, 3] R = c2w[:, :3, :3] # (1) Rotate the world so that z+ is the up axis # we estimate the up axis by averaging the camera up axes ups = np.sum(R * np.array([0, -1.0, 0]), axis=-1) world_up = np.mean(ups, axis=0) world_up /= np.linalg.norm(world_up) up_camspace = np.array([0.0, -1.0, 0.0]) c = (up_camspace * world_up).sum() cross = np.cross(world_up, up_camspace) skew = np.array( [ [0.0, -cross[2], cross[1]], [cross[2], 0.0, -cross[0]], [-cross[1], cross[0], 0.0], ] ) if c > -1: R_align = np.eye(3) + skew + (skew @ skew) * 1 / (1 + c) else: # In the unlikely case the original data has y+ up axis, # rotate 180-deg about x axis R_align = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) # R_align = np.eye(3) # DEBUG R = R_align @ R fwds = np.sum(R * np.array([0, 0.0, 1.0]), axis=-1) t = (R_align @ t[..., None])[..., 0] # (2) Recenter the scene using camera center rays # find the closest point to the origin for each camera's center ray nearest = t + (fwds * -t).sum(-1)[:, None] * fwds # median for more robustness translate = -np.median(nearest, axis=0) # translate = -np.mean(t, axis=0) # DEBUG transform = np.eye(4) transform[:3, 3] = translate transform[:3, :3] = R_align # (3) Rescale the scene using camera distances scale = 1.0 / np.median(np.linalg.norm(t + translate, axis=-1)) return transform, scale def load_lf_data( datadir: str, scene_name: str, train_skip: int, val_skip: int, test_skip: int, cam_scale_factor: float, near: Optional[float], far: Optional[float], ): basedir = os.path.join(datadir, scene_name) def parse_txt(filename): assert os.path.isfile(filename) nums = open(filename).read().split() return np.array([float(x) for x in nums]).reshape([4, 4]).astype(np.float32) # camera parameters files intrinsics_files = find_files( "{}/train/intrinsics".format(basedir), exts=["*.txt"] )[::train_skip] intrinsics_files += find_files( "{}/validation/intrinsics".format(basedir), exts=["*.txt"] )[::val_skip] intrinsics_files += find_files( "{}/test/intrinsics".format(basedir), exts=["*.txt"] )[::test_skip] pose_files = find_files("{}/train/pose".format(basedir), exts=["*.txt"])[ ::train_skip ] pose_files += find_files("{}/validation/pose".format(basedir), exts=["*.txt"])[ ::val_skip ] pose_files += find_files("{}/test/pose".format(basedir), exts=["*.txt"])[ ::test_skip ] cam_cnt = len(pose_files) # img files img_files = find_files("{}/rgb".format(basedir), exts=["*.png", "*.jpg"]) if len(img_files) > 0: assert len(img_files) == cam_cnt else: img_files = [ None, ] * cam_cnt # assume all images have the same size as training image train_imgfile = find_files("{}/train/rgb".format(basedir), exts=["*.png", "*.jpg"])[ ::train_skip ] val_imgfile = find_files( "{}/validation/rgb".format(basedir), exts=["*.png", "*.jpg"] )[::val_skip] test_imgfile = find_files("{}/test/rgb".format(basedir), exts=["*.png", "*.jpg"])[ ::test_skip ] i_train = np.arange(len(train_imgfile)) i_val = np.arange(len(val_imgfile)) + len(train_imgfile) i_test = np.arange(len(test_imgfile)) + len(train_imgfile) + len(val_imgfile) i_all = np.arange(len(train_imgfile) + len(val_imgfile) + len(test_imgfile)) i_split = (i_train, i_val, i_test, i_all) images = ( np.stack( [ imageio.imread(imgfile) for imgfile in train_imgfile + val_imgfile + test_imgfile ] ) / 255.0 ) h, w = images[0].shape[:2] intrinsics = np.stack( [parse_txt(intrinsics_file) for intrinsics_file in intrinsics_files] ) extrinsics = np.stack([parse_txt(pose_file) for pose_file in pose_files]) if cam_scale_factor > 0: T, sscale = similarity_from_cameras(extrinsics) extrinsics = np.einsum("nij, ki -> nkj", extrinsics, T) scene_scale = cam_scale_factor * sscale extrinsics[:, :3, 3] *= scene_scale num_frame = len(extrinsics) image_sizes = np.array([[h, w] for i in range(num_frame)]) near = 0.0 if near is None else near far = 1.0 if far is None else far render_poses = extrinsics return ( images, intrinsics, extrinsics, image_sizes, near, far, (-1, -1), i_split, render_poses, )
null
20,267
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def ptstocam(pts, c2w): tt = np.matmul(c2w[:3, :3].T, (pts - c2w[:3, 3])[..., np.newaxis])[..., 0] return tt
null
20,268
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def normalize(x): return x / np.linalg.norm(x) def viewmatrix(z, up, pos): vec2 = normalize(z) vec1_avg = up vec0 = normalize(np.cross(vec1_avg, vec2)) vec1 = normalize(np.cross(vec2, vec0)) m = np.stack([vec0, vec1, vec2, pos], 1) return m def render_path_spiral(c2w, up, rads, focal, zdelta, zrate, rots, N): render_poses = [] rads = np.array(list(rads) + [1.0]) hwf = c2w[:, 4:5] for theta in np.linspace(0.0, 2.0 * np.pi * rots, N + 1)[:-1]: c = np.dot( c2w[:3, :4], np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0]) * rads, ) z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0]))) render_poses.append(np.concatenate([viewmatrix(z, up, c), hwf], 1)) return render_poses
null
20,269
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def poses_avg(poses): hwf = poses[0, :3, -1:] center = poses[:, :3, 3].mean(0) vec2 = normalize(poses[:, :3, 2].sum(0)) up = poses[:, :3, 1].sum(0) c2w = np.concatenate([viewmatrix(vec2, up, center), hwf], 1) return c2w def recenter_poses(poses): poses_ = poses + 0 bottom = np.reshape([0, 0, 0, 1.0], [1, 4]) c2w = poses_avg(poses) c2w = np.concatenate([c2w[:3, :4], bottom], -2) bottom = np.tile(np.reshape(bottom, [1, 1, 4]), [poses.shape[0], 1, 1]) poses = np.concatenate([poses[:, :3, :4], bottom], -2) poses = np.linalg.inv(c2w) @ poses poses_[:, :3, :4] = poses[:, :3, :4] poses = poses_ return poses
null
20,270
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def normalize(x): return x / np.linalg.norm(x) def spherify_poses(poses, bds): p34_to_44 = lambda p: np.concatenate( [p, np.tile(np.reshape(np.eye(4)[-1, :], [1, 1, 4]), [p.shape[0], 1, 1])], 1 ) rays_d = poses[:, :3, 2:3] rays_o = poses[:, :3, 3:4] def min_line_dist(rays_o, rays_d): A_i = np.eye(3) - rays_d * np.transpose(rays_d, [0, 2, 1]) b_i = -A_i @ rays_o pt_mindist = np.squeeze( -np.linalg.inv((np.transpose(A_i, [0, 2, 1]) @ A_i).mean(0)) @ (b_i).mean(0) ) return pt_mindist pt_mindist = min_line_dist(rays_o, rays_d) center = pt_mindist up = (poses[:, :3, 3] - center).mean(0) vec0 = normalize(up) vec1 = normalize(np.cross([0.1, 0.2, 0.3], vec0)) vec2 = normalize(np.cross(vec0, vec1)) pos = center c2w = np.stack([vec1, vec2, vec0, pos], 1) poses_reset = np.linalg.inv(p34_to_44(c2w[None])) @ p34_to_44(poses[:, :3, :4]) rad = np.sqrt(np.mean(np.sum(np.square(poses_reset[:, :3, 3]), -1))) sc = 1.0 / rad poses_reset[:, :3, 3] *= sc bds *= sc rad *= sc centroid = np.mean(poses_reset[:, :3, 3], 0) zh = centroid[2] radcircle = np.sqrt(rad**2 - zh**2) new_poses = [] for th in np.linspace(0.0, 2.0 * np.pi, 120): camorigin = np.array([radcircle * np.cos(th), radcircle * np.sin(th), zh]) up = np.array([0, 0, -1.0]) vec2 = normalize(camorigin) vec0 = normalize(np.cross(vec2, up)) vec1 = normalize(np.cross(vec2, vec0)) pos = camorigin p = np.stack([vec0, vec1, vec2, pos], 1) new_poses.append(p) new_poses = np.stack(new_poses, 0) new_poses = np.concatenate( [new_poses, np.broadcast_to(poses[0, :3, -1:], new_poses[:, :3, -1:].shape)], -1 ) poses_reset = np.concatenate( [ poses_reset[:, :3, :4], np.broadcast_to(poses[0, :3, -1:], poses_reset[:, :3, -1:].shape), ], -1, ) return poses_reset, new_poses, bds
null
20,271
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def _load_data(basedir, factor=None, width=None, height=None, load_imgs=True): poses_arr = np.load(os.path.join(basedir, "poses_bounds.npy")) poses = poses_arr[:, :-2].reshape([-1, 3, 5]).transpose([1, 2, 0]) bds = poses_arr[:, -2:].transpose([1, 0]) img0 = [ os.path.join(basedir, "images", f) for f in sorted(os.listdir(os.path.join(basedir, "images"))) if f.endswith("JPG") or f.endswith("jpg") or f.endswith("png") ][0] sh = imageio.imread(img0).shape sfx = "" if factor is not None: sfx = "_{}".format(factor) _minify(basedir, factors=[factor]) factor = factor elif height is not None: factor = sh[0] / float(height) width = int(sh[1] / factor) _minify(basedir, resolutions=[[height, width]]) sfx = "_{}x{}".format(width, height) elif width is not None: factor = sh[1] / float(width) height = int(sh[0] / factor) _minify(basedir, resolutions=[[height, width]]) sfx = "_{}x{}".format(width, height) else: factor = 1 imgdir = os.path.join(basedir, "images" + sfx) if not os.path.exists(imgdir): print(imgdir, "does not exist, returning") return imgfiles = [ os.path.join(imgdir, f) for f in sorted(os.listdir(imgdir)) if f.endswith("JPG") or f.endswith("jpg") or f.endswith("png") ] if poses.shape[-1] != len(imgfiles): print( "Mismatch between imgs {} and poses {} !!!!".format( len(imgfiles), poses.shape[-1] ) ) return sh = imageio.imread(imgfiles[0]).shape poses[:2, 4, :] = np.array(sh[:2]).reshape([2, 1]) poses[2, 4, :] = poses[2, 4, :] * 1.0 / factor if not load_imgs: return poses, bds def imread(f): if f.endswith("png"): return imageio.imread(f, ignoregamma=True) else: return imageio.imread(f) imgs = [imread(f)[..., :3] / 255.0 for f in imgfiles] imgs = np.stack(imgs, -1) return poses, bds, imgs def similarity_from_cameras(c2w, strict_scaling): """ Get a similarity transform to normalize dataset from c2w (OpenCV convention) cameras :param c2w: (N, 4) :return T (4,4) , scale (float) """ t = c2w[:, :3, 3] R = c2w[:, :3, :3] # (1) Rotate the world so that z+ is the up axis # we estimate the up axis by averaging the camera up axes ups = np.sum(R * np.array([0, -1.0, 0]), axis=-1) world_up = np.mean(ups, axis=0) world_up /= np.linalg.norm(world_up) up_camspace = np.array([0.0, -1.0, 0.0]) c = (up_camspace * world_up).sum() cross = np.cross(world_up, up_camspace) skew = np.array( [ [0.0, -cross[2], cross[1]], [cross[2], 0.0, -cross[0]], [-cross[1], cross[0], 0.0], ] ) if c > -1: R_align = np.eye(3) + skew + (skew @ skew) * 1 / (1 + c) else: # In the unlikely case the original data has y+ up axis, # rotate 180-deg about x axis R_align = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) # R_align = np.eye(3) # DEBUG R = R_align @ R fwds = np.sum(R * np.array([0, 0.0, 1.0]), axis=-1) t = (R_align @ t[..., None])[..., 0] # (2) Recenter the scene using camera center rays # find the closest point to the origin for each camera's center ray nearest = t + (fwds * -t).sum(-1)[:, None] * fwds # median for more robustness translate = -np.median(nearest, axis=0) # translate = -np.mean(t, axis=0) # DEBUG transform = np.eye(4) transform[:3, 3] = translate transform[:3, :3] = R_align # (3) Rescale the scene using camera distances scale_fn = np.max if strict_scaling else np.median scale = 1.0 / scale_fn(np.linalg.norm(t + translate, axis=-1)) return transform, scale def transform_pose_llff(poses): ret = np.zeros_like(poses) ret[:] = poses[:] ret[:, 0, 1:3] *= -1 ret[:, 1:, 3] *= -1 ret[:, 1:3, 0] *= -1 return ret def load_nerf_360_v2_data( datadir: str, scene_name: str, factor: int, cam_scale_factor: float, train_skip: int, val_skip: int, test_skip: int, near: float, far: float, strict_scaling: bool, ): basedir = os.path.join(datadir, scene_name) poses, bds, imgs = _load_data(basedir, factor=factor) # factor=8 downsamples original imgs by 8x # Correct rotation matrix ordering and move variable dim to axis 0 poses = np.concatenate([poses[:, 1:2, :], -poses[:, 0:1, :], poses[:, 2:, :]], 1) poses = np.moveaxis(poses, -1, 0).astype(np.float32) imgs = np.moveaxis(imgs, -1, 0).astype(np.float32) images = imgs images = images.astype(np.float32) poses = poses.astype(np.float32) num_frame = len(images) # Transforming the coordinate poses = transform_pose_llff(poses) _extrinsics = poses[:, :3, :4] extrinsics = np.stack([np.eye(4) for _ in range(num_frame)]) extrinsics[:, :3, :4] = _extrinsics T, sscale = similarity_from_cameras(extrinsics, strict_scaling) extrinsics = np.einsum("nij, ki -> nkj", extrinsics, T) scene_scale = cam_scale_factor * sscale extrinsics[:, :3, 3] *= scene_scale render_poses = pose_utils.pose_interp(extrinsics, 2)[:10] i_test = np.arange(num_frame)[::10] i_val = np.arange(num_frame)[5::10] i_train = np.array( [i for i in range(num_frame) if not i in i_test and not i in i_val] ) i_train = i_train[::train_skip] i_val = i_val[::val_skip] i_test = i_test[::test_skip] hwf = poses[0, :3, -1] h, w, focal = hwf h, w = int(h), int(w) hwf = [h, w, focal] intrinsics = np.array( [ [[focal, 0.0, 0.5 * w], [0.0, focal, 0.5 * h], [0.0, 0.0, 1.0]] for _ in range(num_frame) ] ) image_sizes = np.array([[h, w] for i in range(num_frame)]) i_all = np.arange(num_frame) i_split = (i_train, i_val, i_test, i_all) ndc_coeffs = (-1.0, -1.0) near = 0.0 if near is None else near far = 1.0 if far is None else far return ( images, intrinsics, extrinsics, image_sizes, near, far, ndc_coeffs, i_split, render_poses, )
null
20,272
import json import os import gdown import imageio import numpy as np import torch def pose_spherical(theta, phi, radius): def load_shiny_blender_data( datadir: str, scene_name: str, train_skip: int, val_skip: int, test_skip: int, cam_scale_factor: float, white_bkgd: bool, ): basedir = os.path.join(datadir, scene_name) cam_trans = np.diag(np.array([1, -1, -1, 1], dtype=np.float32)) splits = ["train", "val", "test"] metas = {} for s in splits: if s == "val": continue with open(os.path.join(basedir, "transforms_{}.json".format(s)), "r") as fp: metas[s] = json.load(fp) metas["val"] = metas["test"] images = [] normals = [] extrinsics = [] counts = [0] for s in splits: meta = metas[s] imgs = [] norms = [] alphas = [] poses = [] if s == "train": skip = train_skip elif s == "val": skip = val_skip elif s == "test": skip = test_skip for frame in meta["frames"][::skip]: img_fname = os.path.join(basedir, frame["file_path"] + ".png") norm_fname = os.path.join(basedir, frame["file_path"] + "_normal.png") imgs.append(imageio.imread(img_fname)) norms.append(imageio.imread(norm_fname)) poses.append(np.array(frame["transform_matrix"])) imgs = (np.array(imgs) / 255.0).astype(np.float32) alphas = imgs[..., -1:] norms = np.array(norms).astype(np.float32)[..., :3] * 2.0 / 255.0 - 1.0 # Concatenate normals and alphas for computing MAE norms = np.concatenate([norms, alphas], axis=-1) poses = np.array(poses).astype(np.float32) counts.append(counts[-1] + imgs.shape[0]) images.append(imgs) normals.append(norms) extrinsics.append(poses) i_split = [np.arange(counts[i], counts[i + 1]) for i in range(3)] images = np.concatenate(images, 0) normals = np.concatenate(normals, 0) extrinsics = np.concatenate(extrinsics, 0) extrinsics[:, :3, 3] *= cam_scale_factor extrinsics = extrinsics @ cam_trans h, w = imgs[0].shape[:2] num_frame = len(extrinsics) i_split += [np.arange(num_frame)] camera_angle_x = float(meta["camera_angle_x"]) focal = 0.5 * w / np.tan(0.5 * camera_angle_x) intrinsics = np.array( [ [[focal, 0.0, 0.5 * w], [0.0, focal, 0.5 * h], [0.0, 0.0, 1.0]] for _ in range(num_frame) ] ) image_sizes = np.array([[h, w] for _ in range(num_frame)]) render_poses = torch.stack( [ pose_spherical(angle, -30.0, 4.0) @ cam_trans for angle in np.linspace(-180, 180, 40 + 1)[:-1] ], 0, ) render_poses[:, :3, 3] *= cam_scale_factor near = 2.0 far = 6.0 if white_bkgd: images = images[..., :3] * images[..., -1:] + (1.0 - images[..., -1:]) else: images = images[..., :3] return ( images, intrinsics, extrinsics, image_sizes, near, far, (-1, -1), i_split, render_poses, normals, )
null
20,273
import os from subprocess import check_output import imageio import numpy as np def ptstocam(pts, c2w): tt = np.matmul(c2w[:3, :3].T, (pts - c2w[:3, 3])[..., np.newaxis])[..., 0] return tt
null
20,274
import os from subprocess import check_output import imageio import numpy as np def normalize(x): def viewmatrix(z, up, pos): def render_path_spiral(c2w, up, rads, focal, zdelta, zrate, rots, N): render_poses = [] rads = np.array(list(rads) + [1.0]) hwf = c2w[:, 4:5] for theta in np.linspace(0.0, 2.0 * np.pi * rots, N + 1)[:-1]: c = np.dot( c2w[:3, :4], np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0]) * rads, ) z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0]))) render_poses.append(np.concatenate([viewmatrix(z, up, c), hwf], 1)) return render_poses
null
20,275
import os from subprocess import check_output import imageio import numpy as np def poses_avg(poses): hwf = poses[0, :3, -1:] center = poses[:, :3, 3].mean(0) vec2 = normalize(poses[:, :3, 2].sum(0)) up = poses[:, :3, 1].sum(0) c2w = np.concatenate([viewmatrix(vec2, up, center), hwf], 1) return c2w def recenter_poses(poses): poses_ = poses + 0 bottom = np.reshape([0, 0, 0, 1.0], [1, 4]) c2w = poses_avg(poses) c2w = np.concatenate([c2w[:3, :4], bottom], -2) bottom = np.tile(np.reshape(bottom, [1, 1, 4]), [poses.shape[0], 1, 1]) poses = np.concatenate([poses[:, :3, :4], bottom], -2) poses = np.linalg.inv(c2w) @ poses poses_[:, :3, :4] = poses[:, :3, :4] poses = poses_ return poses
null
20,276
import os from subprocess import check_output import imageio import numpy as np def normalize(x): return x / np.linalg.norm(x) def spherify_poses(poses, bds): p34_to_44 = lambda p: np.concatenate( [p, np.tile(np.reshape(np.eye(4)[-1, :], [1, 1, 4]), [p.shape[0], 1, 1])], 1 ) rays_d = poses[:, :3, 2:3] rays_o = poses[:, :3, 3:4] def min_line_dist(rays_o, rays_d): A_i = np.eye(3) - rays_d * np.transpose(rays_d, [0, 2, 1]) b_i = -A_i @ rays_o pt_mindist = np.squeeze( -np.linalg.inv((np.transpose(A_i, [0, 2, 1]) @ A_i).mean(0)) @ (b_i).mean(0) ) return pt_mindist pt_mindist = min_line_dist(rays_o, rays_d) center = pt_mindist up = (poses[:, :3, 3] - center).mean(0) vec0 = normalize(up) vec1 = normalize(np.cross([0.1, 0.2, 0.3], vec0)) vec2 = normalize(np.cross(vec0, vec1)) pos = center c2w = np.stack([vec1, vec2, vec0, pos], 1) poses_reset = np.linalg.inv(p34_to_44(c2w[None])) @ p34_to_44(poses[:, :3, :4]) rad = np.sqrt(np.mean(np.sum(np.square(poses_reset[:, :3, 3]), -1))) sc = 1.0 / rad poses_reset[:, :3, 3] *= sc bds *= sc rad *= sc centroid = np.mean(poses_reset[:, :3, 3], 0) zh = centroid[2] radcircle = np.sqrt(rad**2 - zh**2) new_poses = [] for th in np.linspace(0.0, 2.0 * np.pi, 120): camorigin = np.array([radcircle * np.cos(th), radcircle * np.sin(th), zh]) up = np.array([0, 0, -1.0]) vec2 = normalize(camorigin) vec0 = normalize(np.cross(vec2, up)) vec1 = normalize(np.cross(vec2, vec0)) pos = camorigin p = np.stack([vec0, vec1, vec2, pos], 1) new_poses.append(p) new_poses = np.stack(new_poses, 0) new_poses = np.concatenate( [new_poses, np.broadcast_to(poses[0, :3, -1:], new_poses[:, :3, -1:].shape)], -1 ) poses_reset = np.concatenate( [ poses_reset[:, :3, :4], np.broadcast_to(poses[0, :3, -1:], poses_reset[:, :3, -1:].shape), ], -1, ) return poses_reset, new_poses, bds
null
20,277
import os from subprocess import check_output import imageio import numpy as np def _load_data(basedir, factor=None, width=None, height=None, load_imgs=True): def similarity_from_cameras(c2w): def transform_pose_llff(poses): def load_refnerf_real_data( datadir: str, scene_name: str, factor: int, cam_scale_factor: float, train_skip: int, val_skip: int, test_skip: int, ): basedir = os.path.join(datadir, scene_name) poses, bds, imgs = _load_data(basedir, factor=factor) # factor=8 downsamples original imgs by 8x # Correct rotation matrix ordering and move variable dim to axis 0 poses = np.concatenate([poses[:, 1:2, :], -poses[:, 0:1, :], poses[:, 2:, :]], 1) poses = np.moveaxis(poses, -1, 0).astype(np.float32) imgs = np.moveaxis(imgs, -1, 0).astype(np.float32) images = imgs images = images.astype(np.float32) poses = poses.astype(np.float32) num_frame = len(images) # Transforming the coordinate poses = transform_pose_llff(poses) _extrinsics = poses[:, :3, :4] extrinsics = np.stack([np.eye(4) for _ in range(num_frame)]) extrinsics[:, :3, :4] = _extrinsics T, sscale = similarity_from_cameras(extrinsics) extrinsics = np.einsum("nij, ki -> nkj", extrinsics, T) scene_scale = cam_scale_factor * sscale extrinsics[:, :3, 3] *= scene_scale render_poses = extrinsics i_test = np.arange(num_frame)[::10] i_val = np.arange(num_frame)[5::10] i_train = np.array( [i for i in range(num_frame) if not i in i_test and not i in i_val] ) i_train = i_train[::train_skip] i_val = i_val[::val_skip] i_test = i_test[::test_skip] hwf = poses[0, :3, -1] h, w, focal = hwf h, w = int(h), int(w) hwf = [h, w, focal] intrinsics = np.array( [ [[focal, 0.0, 0.5 * w], [0.0, focal, 0.5 * h], [0.0, 0.0, 1.0]] for _ in range(num_frame) ] ) near = 0.0 far = 1.0 image_sizes = np.array([[h, w] for i in range(num_frame)]) i_all = np.arange(num_frame) i_split = (i_train, i_val, i_test, i_all) ndc_coeffs = (-1.0, -1.0) return ( images, intrinsics, extrinsics, image_sizes, near, far, ndc_coeffs, i_split, render_poses, )
null
20,278
import os from subprocess import check_output from typing import * import imageio import numpy as np def ptstocam(pts, c2w): tt = np.matmul(c2w[:3, :3].T, (pts - c2w[:3, 3])[..., np.newaxis])[..., 0] return tt
null
20,279
import os from subprocess import check_output from typing import * import imageio import numpy as np def _load_data(basedir, factor=None, width=None, height=None, load_imgs=True): poses_arr = np.load(os.path.join(basedir, "poses_bounds.npy")) poses = poses_arr[:, :-2].reshape([-1, 3, 5]).transpose([1, 2, 0]) bds = poses_arr[:, -2:].transpose([1, 0]) img0 = [ os.path.join(basedir, "images", f) for f in sorted(os.listdir(os.path.join(basedir, "images"))) if f.endswith("JPG") or f.endswith("jpg") or f.endswith("png") ][0] sh = imageio.imread(img0).shape sfx = "" if factor is not None: sfx = "_{}".format(factor) _minify(basedir, factors=[factor]) factor = factor elif height is not None: factor = sh[0] / float(height) width = int(sh[1] / factor) _minify(basedir, resolutions=[[height, width]]) sfx = "_{}x{}".format(width, height) elif width is not None: factor = sh[1] / float(width) height = int(sh[0] / factor) _minify(basedir, resolutions=[[height, width]]) sfx = "_{}x{}".format(width, height) else: factor = 1 imgdir = os.path.join(basedir, "images" + sfx) if not os.path.exists(imgdir): print(imgdir, "does not exist, returning") return imgfiles = [ os.path.join(imgdir, f) for f in sorted(os.listdir(imgdir)) if f.endswith("JPG") or f.endswith("jpg") or f.endswith("png") ] if poses.shape[-1] != len(imgfiles): print( "Mismatch between imgs {} and poses {} !!!!".format( len(imgfiles), poses.shape[-1] ) ) return sh = imageio.imread(imgfiles[0]).shape poses[:2, 4, :] = np.array(sh[:2]).reshape([2, 1]) poses[2, 4, :] = poses[2, 4, :] * 1.0 / factor if not load_imgs: return poses, bds def imread(f): if f.endswith("png"): return imageio.imread(f, ignoregamma=True) else: return imageio.imread(f) imgs = [imread(f)[..., :3] / 255.0 for f in imgfiles] imgs = np.stack(imgs, -1) return poses, bds, imgs def normalize(x): return x / np.linalg.norm(x) def poses_avg(poses): hwf = poses[0, :3, -1:] center = poses[:, :3, 3].mean(0) vec2 = normalize(poses[:, :3, 2].sum(0)) up = poses[:, :3, 1].sum(0) c2w = np.concatenate([viewmatrix(vec2, up, center), hwf], 1) return c2w def render_path_spiral(c2w, up, rads, focal, zdelta, zrate, rots, N): render_poses = [] rads = np.array(list(rads) + [1.0]) hwf = c2w[:, 4:5] for theta in np.linspace(0.0, 2.0 * np.pi * rots, N + 1)[:-1]: c = np.dot( c2w[:3, :4], np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0]) * rads, ) z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0]))) render_poses.append(np.concatenate([viewmatrix(z, up, c), hwf], 1)) return render_poses def recenter_poses(poses): poses_ = poses + 0 bottom = np.reshape([0, 0, 0, 1.0], [1, 4]) c2w = poses_avg(poses) c2w = np.concatenate([c2w[:3, :4], bottom], -2) bottom = np.tile(np.reshape(bottom, [1, 1, 4]), [poses.shape[0], 1, 1]) poses = np.concatenate([poses[:, :3, :4], bottom], -2) poses = np.linalg.inv(c2w) @ poses poses_[:, :3, :4] = poses[:, :3, :4] poses = poses_ return poses def spherify_poses(poses, bds): p34_to_44 = lambda p: np.concatenate( [p, np.tile(np.reshape(np.eye(4)[-1, :], [1, 1, 4]), [p.shape[0], 1, 1])], 1 ) rays_d = poses[:, :3, 2:3] rays_o = poses[:, :3, 3:4] def min_line_dist(rays_o, rays_d): A_i = np.eye(3) - rays_d * np.transpose(rays_d, [0, 2, 1]) b_i = -A_i @ rays_o pt_mindist = np.squeeze( -np.linalg.inv((np.transpose(A_i, [0, 2, 1]) @ A_i).mean(0)) @ (b_i).mean(0) ) return pt_mindist pt_mindist = min_line_dist(rays_o, rays_d) center = pt_mindist up = (poses[:, :3, 3] - center).mean(0) vec0 = normalize(up) vec1 = normalize(np.cross([0.1, 0.2, 0.3], vec0)) vec2 = normalize(np.cross(vec0, vec1)) pos = center c2w = np.stack([vec1, vec2, vec0, pos], 1) poses_reset = np.linalg.inv(p34_to_44(c2w[None])) @ p34_to_44(poses[:, :3, :4]) rad = np.sqrt(np.mean(np.sum(np.square(poses_reset[:, :3, 3]), -1))) sc = 1.0 / rad poses_reset[:, :3, 3] *= sc bds *= sc rad *= sc centroid = np.mean(poses_reset[:, :3, 3], 0) zh = centroid[2] radcircle = np.sqrt(rad**2 - zh**2) new_poses = [] for th in np.linspace(0.0, 2.0 * np.pi, 120): camorigin = np.array([radcircle * np.cos(th), radcircle * np.sin(th), zh]) up = np.array([0, 0, -1.0]) vec2 = normalize(camorigin) vec0 = normalize(np.cross(vec2, up)) vec1 = normalize(np.cross(vec2, vec0)) pos = camorigin p = np.stack([vec0, vec1, vec2, pos], 1) new_poses.append(p) new_poses = np.stack(new_poses, 0) new_poses = np.concatenate( [new_poses, np.broadcast_to(poses[0, :3, -1:], new_poses[:, :3, -1:].shape)], -1 ) poses_reset = np.concatenate( [ poses_reset[:, :3, :4], np.broadcast_to(poses[0, :3, -1:], poses_reset[:, :3, -1:].shape), ], -1, ) return poses_reset, new_poses, bds def transform_pose_llff(poses): ret = np.zeros_like(poses) ret[:] = poses[:] ret[:, 0, 1:3] *= -1 ret[:, 1:, 3] *= -1 ret[:, 1:3, 0] *= -1 return ret def load_llff_data( datadir: str, scene_name: str, factor: int, ndc_coord: bool, recenter: bool, bd_factor: float, spherify: bool, llffhold: int, path_zflat: bool, near: Optional[float], far: Optional[float], ): basedir = os.path.join(datadir, scene_name) poses, bds, imgs = _load_data(basedir, factor=factor) # factor=8 downsamples original imgs by 8x # Correct rotation matrix ordering and move variable dim to axis 0 poses = np.concatenate([poses[:, 1:2, :], -poses[:, 0:1, :], poses[:, 2:, :]], 1) poses = np.moveaxis(poses, -1, 0).astype(np.float32) imgs = np.moveaxis(imgs, -1, 0).astype(np.float32) images = imgs bds = np.moveaxis(bds, -1, 0).astype(np.float32) # Rescale if bd_factor is provided sc = 1.0 if bd_factor is None else 1.0 / (bds.min() * bd_factor) poses[:, :3, 3] *= sc bds *= sc if recenter: poses = recenter_poses(poses) if spherify: poses, render_poses, bds = spherify_poses(poses, bds) else: c2w = poses_avg(poses) ## Get spiral # Get average pose up = normalize(poses[:, :3, 1].sum(0)) # Find a reasonable "focus depth" for this dataset close_depth, inf_depth = bds.min() * 0.9, bds.max() * 5.0 dt = 0.75 mean_dz = 1.0 / (((1.0 - dt) / close_depth + dt / inf_depth)) focal = mean_dz # Get radii for spiral path shrink_factor = 0.8 zdelta = close_depth * 0.2 tt = poses[:, :3, 3] rads = np.percentile(np.abs(tt), 90, 0) c2w_path = c2w N_views = 120 N_rots = 2 if path_zflat: zloc = -close_depth * 0.1 c2w_path[:3, 3] = c2w_path[:3, 3] + zloc * c2w_path[:3, 2] rads[2] = 0.0 N_rots = 1 N_views /= 2 render_poses = render_path_spiral( c2w_path, up, rads, focal, zdelta, zrate=0.5, rots=N_rots, N=N_views ) c2w = poses_avg(poses) dists = np.sum(np.square(c2w[:3, 3] - poses[:, :3, 3]), -1) i_test = np.argmin(dists) images = images.astype(np.float32) poses = poses.astype(np.float32) # Transforming the coordinate poses = transform_pose_llff(poses) render_poses = np.stack(render_poses)[:, :3, :4] render_poses = transform_pose_llff(render_poses) extrinsics = poses[:, :3, :4] if not isinstance(i_test, list): i_test = [i_test] num_frame = len(poses) hwf = poses[0, :3, -1] h, w, focal = hwf h, w = int(h), int(w) hwf = [h, w, focal] intrinsics = np.array( [ [[focal, 0.0, 0.5 * w], [0.0, focal, 0.5 * h], [0.0, 0.0, 1.0]] for _ in range(num_frame) ] ) if llffhold > 0: i_test = np.arange(num_frame)[::llffhold] i_val = i_test is_train = lambda i: i not in i_test and i not in i_val i_train = np.array([i for i in np.arange(num_frame) if is_train(i)]) if near is None and far is None: near = np.ndarray.min(bds) * 0.9 if not ndc_coord else 0.0 far = np.ndarray.max(bds) * 1.0 if not ndc_coord else 1.0 image_sizes = np.array([[h, w] for i in range(num_frame)]) i_all = np.arange(num_frame) i_split = (i_train, i_val, i_test, i_all) if ndc_coord: ndc_coeffs = (2 * intrinsics[0, 0, 0] / w, 2 * intrinsics[0, 1, 1] / h) else: ndc_coeffs = (-1.0, -1.0) return ( images, intrinsics, extrinsics, image_sizes, near, far, ndc_coeffs, i_split, render_poses, )
null
20,280
import glob import os from typing import * import imageio import numpy as np def find_files(dir, exts): if os.path.isdir(dir): files_grabbed = [] for ext in exts: files_grabbed.extend(glob.glob(os.path.join(dir, ext))) if len(files_grabbed) > 0: files_grabbed = sorted(files_grabbed) return files_grabbed else: return [] def similarity_from_cameras(c2w): """ Get a similarity transform to normalize dataset from c2w (OpenCV convention) cameras :param c2w: (N, 4) :return T (4,4) , scale (float) """ t = c2w[:, :3, 3] R = c2w[:, :3, :3] # (1) Rotate the world so that z+ is the up axis # we estimate the up axis by averaging the camera up axes ups = np.sum(R * np.array([0, -1.0, 0]), axis=-1) world_up = np.mean(ups, axis=0) world_up /= np.linalg.norm(world_up) up_camspace = np.array([0.0, -1.0, 0.0]) c = (up_camspace * world_up).sum() cross = np.cross(world_up, up_camspace) skew = np.array( [ [0.0, -cross[2], cross[1]], [cross[2], 0.0, -cross[0]], [-cross[1], cross[0], 0.0], ] ) if c > -1: R_align = np.eye(3) + skew + (skew @ skew) * 1 / (1 + c) else: # In the unlikely case the original data has y+ up axis, # rotate 180-deg about x axis R_align = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) # R_align = np.eye(3) # DEBUG R = R_align @ R fwds = np.sum(R * np.array([0, 0.0, 1.0]), axis=-1) t = (R_align @ t[..., None])[..., 0] # (2) Recenter the scene using camera center rays # find the closest point to the origin for each camera's center ray nearest = t + (fwds * -t).sum(-1)[:, None] * fwds # median for more robustness translate = -np.median(nearest, axis=0) # translate = -np.mean(t, axis=0) # DEBUG transform = np.eye(4) transform[:3, 3] = translate transform[:3, :3] = R_align # (3) Rescale the scene using camera distances scale = 1.0 / np.median(np.linalg.norm(t + translate, axis=-1)) return transform, scale def load_tnt_data( datadir: str, scene_name: str, train_skip: int, val_skip: int, test_skip: int, cam_scale_factor: float, near: Optional[float], far: Optional[float], ): basedir = os.path.join(datadir, scene_name) def parse_txt(filename): assert os.path.isfile(filename) nums = open(filename).read().split() return np.array([float(x) for x in nums]).reshape([4, 4]).astype(np.float32) # camera parameters files intrinsics_files = find_files( "{}/train/intrinsics".format(basedir), exts=["*.txt"] )[::train_skip] intrinsics_files += find_files( "{}/validation/intrinsics".format(basedir), exts=["*.txt"] )[::val_skip] intrinsics_files += find_files( "{}/test/intrinsics".format(basedir), exts=["*.txt"] )[::test_skip] pose_files = find_files("{}/train/pose".format(basedir), exts=["*.txt"])[ ::train_skip ] pose_files += find_files("{}/validation/pose".format(basedir), exts=["*.txt"])[ ::val_skip ] pose_files += find_files("{}/test/pose".format(basedir), exts=["*.txt"])[ ::test_skip ] cam_cnt = len(pose_files) # img files img_files = find_files("{}/rgb".format(basedir), exts=["*.png", "*.jpg"]) if len(img_files) > 0: assert len(img_files) == cam_cnt else: img_files = [ None, ] * cam_cnt # assume all images have the same size as training image train_imgfile = find_files("{}/train/rgb".format(basedir), exts=["*.png", "*.jpg"])[ ::train_skip ] val_imgfile = find_files( "{}/validation/rgb".format(basedir), exts=["*.png", "*.jpg"] )[::val_skip] test_imgfile = find_files("{}/test/rgb".format(basedir), exts=["*.png", "*.jpg"])[ ::test_skip ] i_train = np.arange(len(train_imgfile)) i_val = np.arange(len(val_imgfile)) + len(train_imgfile) i_test = np.arange(len(test_imgfile)) + len(train_imgfile) + len(val_imgfile) i_all = np.arange(len(train_imgfile) + len(val_imgfile) + len(test_imgfile)) i_split = (i_train, i_val, i_test, i_all) images = ( np.stack( [ imageio.imread(imgfile) for imgfile in train_imgfile + val_imgfile + test_imgfile ] ) / 255.0 ) h, w = images[0].shape[:2] intrinsics = np.stack( [parse_txt(intrinsics_file) for intrinsics_file in intrinsics_files] ) extrinsics = np.stack([parse_txt(pose_file) for pose_file in pose_files]) if cam_scale_factor > 0: T, sscale = similarity_from_cameras(extrinsics) extrinsics = np.einsum("nij, ki -> nkj", extrinsics, T) scene_scale = cam_scale_factor * sscale extrinsics[:, :3, 3] *= scene_scale num_frame = len(extrinsics) image_sizes = np.array([[h, w] for i in range(num_frame)]) near = 0.0 if near is None else near far = 1.0 if far is None else far render_poses = extrinsics return ( images, intrinsics, extrinsics, image_sizes, near, far, (-1, -1), i_split, render_poses, )
null
20,281
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam class MaskedAdam(torch.optim.Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.99), eps=1e-8): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) defaults = dict(lr=lr, betas=betas, eps=eps) self.per_lr = None super(MaskedAdam, self).__init__(params, defaults) def __setstate__(self, state): super(MaskedAdam, self).__setstate__(state) def set_pervoxel_lr(self, count): assert self.param_groups[0]["params"][0].shape == count.shape self.per_lr = count.float() / count.max() def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: lr = group["lr"] beta1, beta2 = group["betas"] eps = group["eps"] skip_zero_grad = group["skip_zero_grad"] for param in group["params"]: if param.grad is not None: state = self.state[param] # Lazy state initialization if len(state) == 0: state["step"] = 0 # Exponential moving average of gradient values state["exp_avg"] = torch.zeros_like( param, memory_format=torch.preserve_format ) # Exponential moving average of squared gradient values state["exp_avg_sq"] = torch.zeros_like( param, memory_format=torch.preserve_format ) state["step"] += 1 from src.model.dvgo.__global__ import adam_upd_cuda if self.per_lr is not None and param.shape == self.per_lr.shape: adam_upd_cuda.adam_upd_with_perlr( param, param.grad, state["exp_avg"], state["exp_avg_sq"], self.per_lr, state["step"], beta1, beta2, lr, eps, ) elif skip_zero_grad: adam_upd_cuda.masked_adam_upd( param, param.grad, state["exp_avg"], state["exp_avg_sq"], state["step"], beta1, beta2, lr, eps, ) else: adam_upd_cuda.adam_upd( param, param.grad, state["exp_avg"], state["exp_avg_sq"], state["step"], beta1, beta2, lr, eps, ) return loss def create_optimizer_or_freeze_model(model, cfg_train, global_step): decay_steps = cfg_train["lrate_decay"] * 1000 decay_factor = 0.1 ** (global_step / decay_steps) param_group = [] for k in cfg_train.keys(): if not k.startswith("lrate_"): continue k = k[len("lrate_") :] if not hasattr(model, k): continue param = getattr(model, k) if param is None: print(f"create_optimizer_or_freeze_model: param {k} not exist") continue lr = cfg_train.get(f"lrate_{k}") * decay_factor if lr > 0: print(f"create_optimizer_or_freeze_model: param {k} lr {lr}") if isinstance(param, nn.Module): param = param.parameters() param_group.append( { "params": param, "lr": lr, "skip_zero_grad": (k in cfg_train["skip_zero_grad_fields"]), } ) else: print(f"create_optimizer_or_freeze_model: param {k} freeze") param.requires_grad = False return MaskedAdam(param_group)
null
20,282
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam def load_checkpoint(model, optimizer, ckpt_path, no_reload_optimizer): ckpt = torch.load(ckpt_path) start = ckpt["global_step"] model.load_state_dict(ckpt["model_state_dict"]) if not no_reload_optimizer: optimizer.load_state_dict(ckpt["optimizer_state_dict"]) return model, optimizer, start
null
20,283
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam def load_model(model_class, ckpt_path): ckpt = torch.load(ckpt_path) model = model_class(**ckpt["model_kwargs"]) model.load_state_dict(ckpt["model_state_dict"]) return model
null
20,284
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam def rgb_ssim( img0, img1, max_val, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03, return_map=False, ): # Modified from https://github.com/google/mipnerf/blob/16e73dfdb52044dcceb47cda5243a686391a6e0f/internal/math.py#L58 assert len(img0.shape) == 3 assert img0.shape[-1] == 3 assert img0.shape == img1.shape # Construct a 1D Gaussian blur filter. hw = filter_size // 2 shift = (2 * hw - filter_size + 1) / 2 f_i = ((np.arange(filter_size) - hw + shift) / filter_sigma) ** 2 filt = np.exp(-0.5 * f_i) filt /= np.sum(filt) # Blur in x and y (faster than the 2D convolution). def convolve2d(z, f): return scipy.signal.convolve2d(z, f, mode="valid") filt_fn = lambda z: np.stack( [ convolve2d(convolve2d(z[..., i], filt[:, None]), filt[None, :]) for i in range(z.shape[-1]) ], -1, ) mu0 = filt_fn(img0) mu1 = filt_fn(img1) mu00 = mu0 * mu0 mu11 = mu1 * mu1 mu01 = mu0 * mu1 sigma00 = filt_fn(img0**2) - mu00 sigma11 = filt_fn(img1**2) - mu11 sigma01 = filt_fn(img0 * img1) - mu01 # Clip the variances and covariances to valid values. # Variance must be non-negative: sigma00 = np.maximum(0.0, sigma00) sigma11 = np.maximum(0.0, sigma11) sigma01 = np.sign(sigma01) * np.minimum(np.sqrt(sigma00 * sigma11), np.abs(sigma01)) c1 = (k1 * max_val) ** 2 c2 = (k2 * max_val) ** 2 numer = (2 * mu01 + c1) * (2 * sigma01 + c2) denom = (mu00 + mu11 + c1) * (sigma00 + sigma11 + c2) ssim_map = numer / denom ssim = np.mean(ssim_map) return ssim_map if return_map else ssim
null
20,285
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam __LPIPS__ = {} def init_lpips(net_name, device): assert net_name in ["alex", "vgg"] import lpips print(f"init_lpips: lpips_{net_name}") return lpips.LPIPS(net=net_name, version="0.1").eval().to(device) def rgb_lpips(np_gt, np_im, net_name, device): if net_name not in __LPIPS__: __LPIPS__[net_name] = init_lpips(net_name, device) gt = torch.from_numpy(np_gt).permute([2, 0, 1]).contiguous().to(device) im = torch.from_numpy(np_im).permute([2, 0, 1]).contiguous().to(device) return __LPIPS__[net_name](gt, im, normalize=True).item()
null
20,286
import functools import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from src.model.dvgo.__global__ import * class DenseGrid(nn.Module): def __init__(self, channels, world_size, xyz_min, xyz_max, **kwargs): super(DenseGrid, self).__init__() self.channels = channels self.world_size = world_size if isinstance(xyz_min, np.ndarray): xyz_min, xyz_max = torch.from_numpy(xyz_min), torch.from_numpy(xyz_max) self.register_buffer("xyz_min", xyz_min.cuda()) self.register_buffer("xyz_max", xyz_max.cuda()) self.grid = nn.Parameter(torch.zeros([1, channels, *world_size]).cuda()) def forward(self, xyz): """ xyz: global coordinates to query """ shape = xyz.shape[:-1] xyz = xyz.reshape(1, 1, 1, -1, 3) ind_norm = ( (xyz.cuda() - self.xyz_min.cuda()) / (self.xyz_max.cuda() - self.xyz_min.cuda()) ).flip((-1,)) * 2 - 1 out = F.grid_sample(self.grid, ind_norm, mode="bilinear", align_corners=True) out = out.reshape(self.channels, -1).T.reshape(*shape, self.channels) if self.channels == 1: out = out.squeeze(-1) return out def scale_volume_grid(self, new_world_size): if self.channels == 0: self.grid = nn.Parameter(torch.zeros([1, self.channels, *new_world_size])) else: self.grid = nn.Parameter( F.interpolate( self.grid.data, size=tuple(new_world_size), mode="trilinear", align_corners=True, ) ) def total_variation_add_grad(self, wx, wy, wz, dense_mode): """Add gradients by total variation loss in-place""" from src.model.dvgo.__global__ import total_variation_cuda total_variation_cuda.total_variation_add_grad( self.grid, self.grid.grad, wx, wy, wz, dense_mode ) def get_dense_grid(self): return self.grid def __isub__(self, val): self.grid.data -= val return self def extra_repr(self): return f"channels={self.channels}, world_size={self.world_size.tolist()}" class TensoRFGrid(nn.Module): def __init__(self, channels, world_size, xyz_min, xyz_max, config): super(TensoRFGrid, self).__init__() self.channels = channels self.world_size = world_size self.config = config self.register_buffer("xyz_min", torch.Tensor(xyz_min)) self.register_buffer("xyz_max", torch.Tensor(xyz_max)) X, Y, Z = world_size R = config["n_comp"] Rxy = config.get("n_comp_xy", R) self.xy_plane = nn.Parameter(torch.randn([1, Rxy, X, Y]) * 0.1) self.xz_plane = nn.Parameter(torch.randn([1, R, X, Z]) * 0.1) self.yz_plane = nn.Parameter(torch.randn([1, R, Y, Z]) * 0.1) self.x_vec = nn.Parameter(torch.randn([1, R, X, 1]) * 0.1) self.y_vec = nn.Parameter(torch.randn([1, R, Y, 1]) * 0.1) self.z_vec = nn.Parameter(torch.randn([1, Rxy, Z, 1]) * 0.1) if self.channels > 1: self.f_vec = nn.Parameter(torch.ones([R + R + Rxy, channels])) nn.init.kaiming_uniform_(self.f_vec, a=np.sqrt(5)) def forward(self, xyz): """ xyz: global coordinates to query """ shape = xyz.shape[:-1] xyz = xyz.reshape(1, 1, -1, 3) ind_norm = (xyz - self.xyz_min) / (self.xyz_max - self.xyz_min) * 2 - 1 ind_norm = torch.cat([ind_norm, torch.zeros_like(ind_norm[..., [0]])], dim=-1) if self.channels > 1: out = compute_tensorf_feat( self.xy_plane, self.xz_plane, self.yz_plane, self.x_vec, self.y_vec, self.z_vec, self.f_vec, ind_norm, ) out = out.reshape(*shape, self.channels) else: out = compute_tensorf_val( self.xy_plane, self.xz_plane, self.yz_plane, self.x_vec, self.y_vec, self.z_vec, ind_norm, ) out = out.reshape(*shape) return out def scale_volume_grid(self, new_world_size): if self.channels == 0: return X, Y, Z = new_world_size self.xy_plane = nn.Parameter( F.interpolate( self.xy_plane.data, size=[X, Y], mode="bilinear", align_corners=True ) ) self.xz_plane = nn.Parameter( F.interpolate( self.xz_plane.data, size=[X, Z], mode="bilinear", align_corners=True ) ) self.yz_plane = nn.Parameter( F.interpolate( self.yz_plane.data, size=[Y, Z], mode="bilinear", align_corners=True ) ) self.x_vec = nn.Parameter( F.interpolate( self.x_vec.data, size=[X, 1], mode="bilinear", align_corners=True ) ) self.y_vec = nn.Parameter( F.interpolate( self.y_vec.data, size=[Y, 1], mode="bilinear", align_corners=True ) ) self.z_vec = nn.Parameter( F.interpolate( self.z_vec.data, size=[Z, 1], mode="bilinear", align_corners=True ) ) def total_variation_add_grad(self, wx, wy, wz, dense_mode): """Add gradients by total variation loss in-place""" loss = ( wx * F.smooth_l1_loss( self.xy_plane[:, :, 1:], self.xy_plane[:, :, :-1], reduction="sum" ) + wy * F.smooth_l1_loss( self.xy_plane[:, :, :, 1:], self.xy_plane[:, :, :, :-1], reduction="sum" ) + wx * F.smooth_l1_loss( self.xz_plane[:, :, 1:], self.xz_plane[:, :, :-1], reduction="sum" ) + wz * F.smooth_l1_loss( self.xz_plane[:, :, :, 1:], self.xz_plane[:, :, :, :-1], reduction="sum" ) + wy * F.smooth_l1_loss( self.yz_plane[:, :, 1:], self.yz_plane[:, :, :-1], reduction="sum" ) + wz * F.smooth_l1_loss( self.yz_plane[:, :, :, 1:], self.yz_plane[:, :, :, :-1], reduction="sum" ) + wx * F.smooth_l1_loss( self.x_vec[:, :, 1:], self.x_vec[:, :, :-1], reduction="sum" ) + wy * F.smooth_l1_loss( self.y_vec[:, :, 1:], self.y_vec[:, :, :-1], reduction="sum" ) + wz * F.smooth_l1_loss( self.z_vec[:, :, 1:], self.z_vec[:, :, :-1], reduction="sum" ) ) loss /= 6 loss.backward() def get_dense_grid(self): if self.channels > 1: feat = torch.cat( [ torch.einsum( "rxy,rz->rxyz", self.xy_plane[0], self.z_vec[0, :, :, 0] ), torch.einsum( "rxz,ry->rxyz", self.xz_plane[0], self.y_vec[0, :, :, 0] ), torch.einsum( "ryz,rx->rxyz", self.yz_plane[0], self.x_vec[0, :, :, 0] ), ] ) grid = torch.einsum("rxyz,rc->cxyz", feat, self.f_vec)[None] else: grid = ( torch.einsum("rxy,rz->xyz", self.xy_plane[0], self.z_vec[0, :, :, 0]) + torch.einsum("rxz,ry->xyz", self.xz_plane[0], self.y_vec[0, :, :, 0]) + torch.einsum("ryz,rx->xyz", self.yz_plane[0], self.x_vec[0, :, :, 0]) ) grid = grid[None, None] return grid def extra_repr(self): return f'channels={self.channels}, world_size={self.world_size.tolist()}, n_comp={self.config["n_comp"]}' def create_grid(type, **kwargs): if type == "DenseGrid": return DenseGrid(**kwargs) elif type == "TensoRFGrid": return TensoRFGrid(**kwargs) else: raise NotImplementedError
null
20,287
import functools import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from src.model.dvgo.__global__ import * def compute_tensorf_feat( xy_plane, xz_plane, yz_plane, x_vec, y_vec, z_vec, f_vec, ind_norm ): # Interp feature (feat shape: [n_pts, n_comp]) xy_feat = ( F.grid_sample( xy_plane, ind_norm[:, :, :, [1, 0]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) xz_feat = ( F.grid_sample( xz_plane, ind_norm[:, :, :, [2, 0]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) yz_feat = ( F.grid_sample( yz_plane, ind_norm[:, :, :, [2, 1]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) x_feat = ( F.grid_sample( x_vec, ind_norm[:, :, :, [3, 0]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) y_feat = ( F.grid_sample( y_vec, ind_norm[:, :, :, [3, 1]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) z_feat = ( F.grid_sample( z_vec, ind_norm[:, :, :, [3, 2]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) # Aggregate components feat = torch.cat( [ xy_feat * z_feat, xz_feat * y_feat, yz_feat * x_feat, ], dim=-1, ) feat = torch.mm(feat, f_vec) return feat
null
20,288
import functools import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from src.model.dvgo.__global__ import * def compute_tensorf_val(xy_plane, xz_plane, yz_plane, x_vec, y_vec, z_vec, ind_norm): # Interp feature (feat shape: [n_pts, n_comp]) xy_feat = ( F.grid_sample( xy_plane, ind_norm[:, :, :, [1, 0]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) xz_feat = ( F.grid_sample( xz_plane, ind_norm[:, :, :, [2, 0]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) yz_feat = ( F.grid_sample( yz_plane, ind_norm[:, :, :, [2, 1]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) x_feat = ( F.grid_sample( x_vec, ind_norm[:, :, :, [3, 0]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) y_feat = ( F.grid_sample( y_vec, ind_norm[:, :, :, [3, 1]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) z_feat = ( F.grid_sample( z_vec, ind_norm[:, :, :, [3, 2]], mode="bilinear", align_corners=True ) .flatten(0, 2) .T ) # Aggregate components feat = ( (xy_feat * z_feat).sum(-1) + (xz_feat * y_feat).sum(-1) + (yz_feat * x_feat).sum(-1) ) return feat
null
20,289
import functools import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch_scatter import segment_coo import src.model.dvgo.grid as grid from src.model.dvgo.__global__ import * from src.model.dvgo.dvgo import Alphas2Weights, Raw2Alpha def create_full_step_id(shape): ray_id = torch.arange(shape[0]).view(-1, 1).expand(shape).flatten() step_id = torch.arange(shape[1]).view(1, -1).expand(shape).flatten() return ray_id, step_id
null
20,290
import os from torch.utils.cpp_extension import load root_dir = __file__.split(os.path.relpath(__file__))[0] render_utils_cuda = None total_variation_cuda = None ub360_utils_cuda = None adam_upd_cuda = None sources = ["lib/dvgo/cuda/adam_upd.cpp", "lib/dvgo/cuda/adam_upd_kernel.cu"] def init(): global render_utils_cuda render_utils_cuda = load( name="render_utils_cuda", sources=[ os.path.join(root_dir, path) for path in [ "lib/dvgo/cuda/render_utils.cpp", "lib/dvgo/cuda/render_utils_kernel.cu", ] ], verbose=True, ) global ub360_utils_cuda ub360_utils_cuda = load( name="ub360_utils_cuda", sources=[ os.path.join(root_dir, path) for path in [ "lib/dvgo/cuda/ub360_utils.cpp", "lib/dvgo/cuda/ub360_utils_kernel.cu", ] ], verbose=True, ) global total_variation_cuda if total_variation_cuda is None: total_variation_cuda = load( name="total_variation_cuda", sources=[ os.path.join(root_dir, path) for path in [ "lib/dvgo/cuda/total_variation.cpp", "lib/dvgo/cuda/total_variation_kernel.cu", ] ], verbose=True, ) global adam_upd_cuda adam_upd_cuda = load( name="adam_upd_cuda", sources=[os.path.join(root_dir, path) for path in sources], verbose=True, )
null