repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
Open-Sora
setup.py
.py
from typing import List from setuptools import find_packages, setup def fetch_requirements(paths) -> List[str]: """ This function reads the requirements file. Args: path (str): the path to the requirements file. Returns: The lines in the requirements file. """ if not isinsta...
77
2,148
Open-Sora
opensora/registry.py
.py
from copy import deepcopy import torch.nn as nn from mmengine.registry import Registry def build_module(module: dict | nn.Module, builder: Registry, **kwargs) -> nn.Module | None: """Build module from config or return the module itself. Args: module (dict | nn.Module): The module to build. b...
42
1,048
Open-Sora
opensora/acceleration/checkpoint.py
.py
import warnings from collections.abc import Iterable from typing import Callable, ContextManager, Optional, Tuple import torch import torch.nn as nn from colossalai.utils import get_current_device from torch.utils.checkpoint import ( _DEFAULT_DETERMINISM_MODE, CheckpointFunction, _checkpoint_without_reentr...
272
12,437
Open-Sora
opensora/acceleration/communications.py
.py
import torch import torch.distributed as dist # ==================== # All-To-All # ==================== def _all_to_all( input_: torch.Tensor, world_size: int, group: dist.ProcessGroup, scatter_dim: int, gather_dim: int, ): input_list = [t.contiguous() for t in torch.tensor_split(input_, worl...
189
5,329
Open-Sora
opensora/acceleration/parallel_states.py
.py
import torch.distributed as dist _GLOBAL_PARALLEL_GROUPS = dict() def set_data_parallel_group(group: dist.ProcessGroup): _GLOBAL_PARALLEL_GROUPS["data"] = group def get_data_parallel_group(get_mixed_dp_pg : bool = False): if get_mixed_dp_pg and "mixed_dp_group" in _GLOBAL_PARALLEL_GROUPS: return _G...
30
823
Open-Sora
opensora/acceleration/shardformer/modeling/t5.py
.py
import torch import torch.nn as nn class T5LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Construct a layernorm module in the T5 style. No bias and no subtraction of mean. """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) ...
40
1,778
Open-Sora
opensora/acceleration/shardformer/policy/t5_encoder.py
.py
from colossalai.shardformer.modeling.jit import get_jit_fused_dropout_add_func from colossalai.shardformer.modeling.t5 import get_jit_fused_T5_layer_ff_forward, get_T5_layer_self_attention_forward from colossalai.shardformer.policies.base_policy import Policy, SubModuleReplacementDescription class T5EncoderPolicy(Pol...
42
1,495
Open-Sora
opensora/datasets/utils.py
.py
import math import os import random import re from typing import Any import numpy as np import pandas as pd import requests import torch import torch.distributed as dist import torchvision import torchvision.transforms as transforms from PIL import Image from torchvision.datasets.folder import IMG_EXTENSIONS, pil_load...
420
14,154
Open-Sora
opensora/datasets/video_transforms.py
.py
# Copyright 2024 Vchitect/Latte # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, ...
596
18,574
Open-Sora
opensora/datasets/bucket.py
.py
from collections import OrderedDict import numpy as np from opensora.utils.logger import log_message from .aspect import get_closest_ratio, get_resolution_with_aspect_ratio from .utils import map_target_fps class Bucket: def __init__(self, bucket_config: dict[str, dict[int, tuple[float, int] | tuple[tuple[floa...
140
5,526
Open-Sora
opensora/datasets/datasets.py
.py
import os import random import numpy as np import pandas as pd import torch from PIL import ImageFile from torchvision.datasets.folder import pil_loader from opensora.registry import DATASETS from .read_video import read_video from .utils import get_transforms_image, get_transforms_video, is_img, map_target_fps, rea...
316
11,134
Open-Sora
opensora/datasets/parallel.py
.py
import multiprocessing from itertools import count from multiprocessing.managers import SyncManager from typing import Any, Callable, Dict, Tuple, Type, cast import dill import pandarallel import pandas as pd from pandarallel.data_types import DataType from pandarallel.progress_bars import ProgressBarsType, get_progre...
177
5,840
Open-Sora
opensora/datasets/aspect.py
.py
import math import os ASPECT_RATIO_LD_LIST = [ # width:height "2.39:1", # cinemascope, 2.39 "2:1", # rare, 2 "16:9", # rare, 1.89 "1.85:1", # american widescreen, 1.85 "9:16", # popular, 1.78 "5:8", # rare, 1.6 "3:2", # rare, 1.5 "4:3", # classic, 1.33 "1:1", # square ] ...
152
5,089
Open-Sora
opensora/datasets/pin_memory_cache.py
.py
import threading from typing import Dict, List, Optional import torch class PinMemoryCache: force_dtype: Optional[torch.dtype] = None min_cache_numel: int = 0 pre_alloc_numels: List[int] = [] def __init__(self): self.cache: Dict[int, torch.Tensor] = {} self.output_to_cache: Dict[int,...
77
3,263
Open-Sora
opensora/datasets/dataloader.py
.py
import collections import functools import os import queue import random import threading import numpy as np import torch import torch.multiprocessing as multiprocessing from torch._utils import ExceptionWrapper from torch.distributed import ProcessGroup from torch.utils.data import DataLoader, _utils from torch.utils...
403
14,667
Open-Sora
opensora/datasets/read_video.py
.py
import gc import math import os import re import warnings from fractions import Fraction import av import cv2 import numpy as np import torch from torchvision import get_video_backend from torchvision.io.video import _check_av_available MAX_NUM_FRAMES = 2500 def read_video_av( filename: str, start_pts: floa...
258
9,449
Open-Sora
opensora/datasets/sampler.py
.py
from collections import OrderedDict, defaultdict from typing import Iterator import numpy as np import torch import torch.distributed as dist from torch.utils.data import Dataset, DistributedSampler from opensora.utils.logger import log_message from opensora.utils.misc import format_numel_str from .aspect import get...
394
15,870
Open-Sora
opensora/utils/ckpt.py
.py
import functools import json import operator import os import re import shutil from glob import glob from typing import Dict, Optional import torch import torch.distributed as dist import torch.nn as nn from colossalai.booster import Booster from colossalai.checkpoint_io import GeneralCheckpointIO from colossalai.util...
525
20,397
Open-Sora
opensora/utils/logger.py
.py
import logging import os import torch.distributed as dist def is_distributed() -> bool: """ Check if the code is running in a distributed setting. Returns: bool: True if running in a distributed setting, False otherwise """ return os.environ.get("WORLD_SIZE", None) is not None def is_m...
91
2,348
Open-Sora
opensora/utils/inference.py
.py
import copy import os import re from enum import Enum import torch from torch import nn from opensora.datasets import save_sample from opensora.datasets.aspect import get_image_size from opensora.datasets.utils import read_from_path, rescale_image_by_path from opensora.utils.logger import log_message from opensora.ut...
352
12,491
Open-Sora
opensora/utils/misc.py
.py
import os import time from collections import OrderedDict from collections.abc import Sequence from contextlib import nullcontext import numpy as np import psutil import torch import torch.distributed as dist import torch.nn as nn from colossalai.cluster.dist_coordinator import DistCoordinator from torch.utils.tensorb...
439
13,863
Open-Sora
opensora/utils/prompt_refine.py
.py
import base64 import os from mimetypes import guess_type from openai import OpenAI sys_prompt_t2v = """You are part of a team of bots that creates videos. The workflow is that you first create a caption of the video, and then the assistant bot will generate the video based on the caption. You work with an assistant b...
235
15,254
Open-Sora
opensora/utils/train.py
.py
import random import warnings from collections import OrderedDict from datetime import timedelta import torch import torch.distributed as dist import torch.nn.functional as F from colossalai.booster.plugin import HybridParallelPlugin, LowLevelZeroPlugin from colossalai.cluster import DistCoordinator from colossalai.ut...
459
20,616
Open-Sora
opensora/utils/sampling.py
.py
import math import os import random from abc import ABC, abstractmethod from dataclasses import dataclass, replace import torch from einops import rearrange, repeat from mmengine.config import Config from peft import PeftModel from torch import Tensor, nn from opensora.datasets.aspect import get_image_size from opens...
727
22,674
Open-Sora
opensora/utils/cai.py
.py
import colossalai import torch import torch.distributed as dist from colossalai.booster import Booster from colossalai.cluster import DistCoordinator from opensora.acceleration.parallel_states import ( get_sequence_parallel_group, get_tensor_parallel_group, set_sequence_parallel_group, ) from opensora.mode...
92
2,951
Open-Sora
opensora/utils/config.py
.py
import argparse import ast import json import os from datetime import datetime import torch from mmengine.config import Config from .logger import is_distributed, is_main_process def parse_args() -> tuple[str, argparse.Namespace]: """ This function parses the command line arguments. Returns: tu...
214
6,341
Open-Sora
opensora/utils/optimizer.py
.py
import torch from colossalai.nn.lr_scheduler import CosineAnnealingWarmupLR from colossalai.nn.optimizer import HybridAdam from torch.optim.lr_scheduler import _LRScheduler def create_optimizer( model: torch.nn.Module, optimizer_config: dict, ) -> torch.optim.Optimizer: """ Create an optimizer. A...
92
3,074
Open-Sora
opensora/models/text/conditioner.py
.py
from colossalai.shardformer import ShardConfig, ShardFormer from torch import Tensor, nn from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5Tokenizer from opensora.acceleration.shardformer.policy.t5_encoder import T5EncoderPolicy from opensora.registry import MODELS @MODELS.register_module("tex...
75
2,954
Open-Sora
opensora/models/mmdit/distributed.py
.py
from functools import partial from typing import Dict, List, Optional, Tuple, Union import torch import torch.distributed as dist import torch.nn as nn from colossalai.shardformer.layer import (FusedLinear1D_Col, FusedLinear1D_Row, Linear1D_Col, Linear1D_Row) from colossalai.s...
884
38,230
Open-Sora
opensora/models/mmdit/model.py
.py
# Modified from Flux # # Copyright 2024 Black Forest Labs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law...
304
9,698
Open-Sora
opensora/models/mmdit/policy.py
.py
from functools import partial from typing import Dict, Union import torch.nn as nn from colossalai.shardformer.policies.base_policy import ModulePolicyDescription, Policy, SubModuleReplacementDescription from opensora.models.vae.tensor_parallel import Conv3dTPCol, Conv3dTPRow, GroupNormTP from .distributed import Co...
156
6,199
Open-Sora
opensora/models/mmdit/math.py
.py
import torch from einops import rearrange from flash_attn import flash_attn_func as flash_attn_func_v2 from liger_kernel.ops.rope import LigerRopeFunction from torch import Tensor from typing import Tuple try: from flash_attn_interface import flash_attn_func as flash_attn_func_v3 SUPPORT_FA3 = True except: ...
118
4,054
Open-Sora
opensora/models/mmdit/layers.py
.py
# Modified from Flux # # Copyright 2024 Black Forest Labs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law...
403
15,544
Open-Sora
opensora/models/vae/utils.py
.py
import math import numpy as np import torch import torch.nn.functional as F from torch import Tensor, nn NUMEL_LIMIT = 2**30 def ceil_to_divisible(n: int, dividend: int) -> int: return math.ceil(dividend / (dividend // n)) def chunked_avg_pool1d(input, kernel_size, stride=None, padding=0, ceil_mode=False, cou...
258
9,850
Open-Sora
opensora/models/vae/losses.py
.py
import torch import torch.nn.functional as F from einops import rearrange from torch import Tensor, nn from opensora.models.vae.lpips import LPIPS def hinge_d_loss(logits_real, logits_fake): loss_real = torch.mean(F.relu(1.0 - logits_real)) loss_fake = torch.mean(F.relu(1.0 + logits_fake)) d_loss = 0.5 *...
224
7,337
Open-Sora
opensora/models/vae/tensor_parallel.py
.py
from typing import List, Optional, Union import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from colossalai.device.device_mesh import DeviceMesh from colossalai.shardformer.layer._operation import ( gather_forward_split_backward, reduce_forward, split_forwar...
559
19,054
Open-Sora
opensora/models/vae/lpips.py
.py
import hashlib import os from collections import namedtuple import requests import torch import torch.nn as nn from torchvision import models from tqdm import tqdm from opensora.acceleration.checkpoint import checkpoint URL_MAP = {"vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"} CKPT_MA...
187
6,974
Open-Sora
opensora/models/vae/autoencoder_2d.py
.py
# Modified from Flux # # Copyright 2024 Black Forest Labs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law...
340
11,853
Open-Sora
opensora/models/vae/discriminator.py
.py
import os import torch.nn as nn from opensora.registry import MODELS from opensora.utils.ckpt import load_checkpoint def weights_init(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm") != -1: nn...
110
3,511
Open-Sora
opensora/models/dc_ae/ae_model_zoo.py
.py
# Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
85
2,957
Open-Sora
opensora/models/dc_ae/utils/list.py
.py
# Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
69
1,854
Open-Sora
opensora/models/dc_ae/utils/init.py
.py
# Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
63
2,410
Open-Sora
opensora/models/dc_ae/models/dc_ae.py
.py
# Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
816
31,225
Open-Sora
opensora/models/dc_ae/models/nn/norm.py
.py
# Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
99
3,426
Open-Sora
opensora/models/dc_ae/models/nn/act.py
.py
# Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
45
1,256
Open-Sora
opensora/models/dc_ae/models/nn/ops.py
.py
# Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
979
30,376
Open-Sora
opensora/models/dc_ae/models/nn/vo_ops.py
.py
import math from inspect import signature from typing import Any, Callable, Optional, Union import torch import torch.nn.functional as F VERBOSE = False def pixel_shuffle_3d(x, upscale_factor): """ 3D pixelshuffle 操作。 """ B, C, T, H, W = x.shape r = upscale_factor assert C % (r * r * r) == 0...
245
7,920
Open-Sora
opensora/models/hunyuan_vae/unet_causal_3d_blocks.py
.py
# Modified from diffusers==0.29.2 and HunyuanVideo # # Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org...
477
16,246
Open-Sora
opensora/models/hunyuan_vae/distributed.py
.py
from typing import List, Optional, Tuple import torch import torch.distributed as dist from colossalai.shardformer.layer._operation import gather_forward_split_backward, split_forward_gather_backward from colossalai.shardformer.layer.attn import RingComm, _rescale_out_lse from colossalai.shardformer.layer.utils import...
581
22,825
Open-Sora
opensora/models/hunyuan_vae/autoencoder_kl_causal_3d.py
.py
# Modified from diffusers==0.29.2 and HunyuanVideo # # Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/...
639
26,473
Open-Sora
opensora/models/hunyuan_vae/vae.py
.py
# Modified from HunyuanVideo # # Copyright 2024 HunyuanVideo # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass from typing import Optional, Tuple import numpy as np import torch import torch.nn as nn from diffus...
341
12,792
Open-Sora
scripts/diffusion/inference.py
.py
import os import time import warnings from pprint import pformat warnings.filterwarnings("ignore", category=FutureWarning) warnings.filterwarnings("ignore", category=UserWarning) import torch import torch.distributed as dist from colossalai.utils import set_seed from tqdm import tqdm from opensora.acceleration.paral...
246
9,476
Open-Sora
scripts/diffusion/train.py
.py
import gc import math import os import subprocess import warnings from contextlib import nullcontext from copy import deepcopy from pprint import pformat warnings.filterwarnings("ignore", category=FutureWarning) warnings.filterwarnings("ignore", category=UserWarning) gc.disable() import torch import torch.distribute...
655
26,337
Open-Sora
scripts/vae/inference.py
.py
import os from pprint import pformat import colossalai import torch from colossalai.utils import get_current_device, set_seed from tqdm import tqdm from opensora.acceleration.parallel_states import get_data_parallel_group from opensora.datasets import save_sample from opensora.datasets.dataloader import prepare_datal...
143
5,182
Open-Sora
scripts/vae/stats.py
.py
from pprint import pformat import colossalai import torch from colossalai.utils import get_current_device, set_seed from tqdm import tqdm from opensora.acceleration.parallel_states import get_data_parallel_group from opensora.datasets.dataloader import prepare_dataloader from opensora.registry import DATASETS, MODELS...
119
4,129
Open-Sora
scripts/vae/train.py
.py
import gc import os import random import subprocess import warnings from contextlib import nullcontext from copy import deepcopy from pprint import pformat warnings.filterwarnings("ignore", category=FutureWarning) warnings.filterwarnings("ignore", category=UserWarning) gc.disable() import torch import torch.distribu...
598
25,664
Open-Sora
scripts/cnv/shard.py
.py
import os import pandas as pd from tqdm import tqdm try: import dask.dataframe as dd SUPPORT_DASK = True except: SUPPORT_DASK = False def shard_parquet(input_path, k): # 检查输入路径是否存在 if not os.path.exists(input_path): raise FileNotFoundError(f"Input file {input_path} does not exist.") ...
75
2,037
Open-Sora
scripts/cnv/meta.py
.py
import argparse import numpy as np import pandas as pd from pandarallel import pandarallel from torchvision.io.video import read_video from tqdm import tqdm def set_parallel(num_workers: int = None) -> callable: if num_workers == 0: return lambda x, *args, **kwargs: x.progress_apply(*args, **kwargs) ...
71
1,965
Open-Sora
gradio/app.py
.py
#!/usr/bin/env python """ This script runs a Gradio App for the Open-Sora model. Usage: python demo.py <config-path> """ import argparse import datetime import importlib import os import subprocess import sys from tempfile import NamedTemporaryFile import spaces import torch import gradio as gr MODEL_TYPES = [...
759
27,346
Open-Sora
configs/diffusion/train/stage1_i2v.py
.py
_base_ = ["stage1.py"] # Define model components model = dict(cond_embed=True) condition_config = dict( t2v=1, i2v_head=5, # train i2v (image as first frame) with weight 5 i2v_loop=1, # train image connection with weight 1 i2v_tail=1, # train i2v (image as last frame) with weight 1 ) lr = 1e-5 opt...
15
337
Open-Sora
configs/diffusion/train/image.py
.py
# Dataset settings dataset = dict( type="video_text", transform_name="resize_crop", fps_max=24, # the desired fps for training vmaf=True, # load vmaf scores into text ) grad_ckpt_settings = (8, 100) # set the grad checkpoint settings bucket_config = { "256px": {1: (1.0, 50)}, "768px": {1: (0...
115
2,421
Open-Sora
configs/diffusion/train/stage2.py
.py
_base_ = ["image.py"] # new config grad_ckpt_settings = (100, 100) plugin = "hybrid" plugin_config = dict( tp_size=1, pp_size=1, sp_size=4, sequence_parallelism_mode="ring_attn", enable_sequence_parallelism=True, static_graph=True, zero_stage=2, ) bucket_config = { "_delete_": True, ...
95
1,943
Open-Sora
configs/diffusion/train/demo.py
.py
_base_ = ["stage1.py"] bucket_config = { "_delete_": True, "256px": { 1: (1.0, 1), 33: (1.0, 1), 97: (1.0, 1), 129: (1.0, 1), }, }
13
177
Open-Sora
configs/diffusion/train/stage1.py
.py
_base_ = ["image.py"] dataset = dict(memory_efficient=False) # new config grad_ckpt_settings = (8, 100) bucket_config = { "_delete_": True, "256px": { 1: (1.0, 45), 5: (1.0, 12), 9: (1.0, 12), 13: (1.0, 12), 17: (1.0, 12), 21: (1.0, 12), 25: (1.0, 12), ...
57
1,118
Open-Sora
configs/diffusion/train/stage2_i2v.py
.py
_base_ = ["stage2.py"] # Define model components model = dict(cond_embed=True) grad_ckpt_buffer_size = 25 * 1024**3 condition_config = dict( t2v=1, i2v_head=5, i2v_loop=1, i2v_tail=1, ) is_causal_vae = True bucket_config = { "_delete_": True, "256px": { 1: (1.0, 195), 5: (1.0,...
88
1,817
Open-Sora
configs/diffusion/train/high_compression.py
.py
_base_ = ["image.py"] bucket_config = { "_delete_": True, "768px": { 1: (1.0, 20), 16: (1.0, 8), 20: (1.0, 8), 24: (1.0, 8), 28: (1.0, 8), 32: (1.0, 8), 36: (1.0, 4), 40: (1.0, 4), 44: (1.0, 4), 48: (1.0, 4), 52: (1.0, 4), ...
72
1,449
Open-Sora
configs/diffusion/inference/768px.py
.py
_base_ = [ # inherit grammer from mmengine "256px.py", "plugins/sp.py", # use sequence parallel ] sampling_option = dict( resolution="768px", )
9
159
Open-Sora
configs/diffusion/inference/t2i2v_768px.py
.py
_base_ = [ # inherit grammer from mmengine "768px.py", "plugins/t2i2v.py", ]
5
86
Open-Sora
configs/diffusion/inference/t2i2v_256px.py
.py
_base_ = [ # inherit grammer from mmengine "256px.py", "plugins/t2i2v.py", ]
5
86
Open-Sora
configs/diffusion/inference/256px.py
.py
save_dir = "samples" # save directory seed = 42 # random seed (except seed for z) batch_size = 1 dtype = "bf16" cond_type = "t2v" # conditional inference options: # t2v: text-to-video # i2v_head: image-to-video (head) # i2v_tail: image-to-video (tail) # i2v_loop: connect images # v2v_head_half: video extension with ...
77
2,054
Open-Sora
configs/diffusion/inference/high_compression.py
.py
_base_ = ["t2i2v_768px.py"] # no need for parallelism plugin = None plugin_config = None plugin_ae = None plugin_config_ae = None # model settings patch_size = 1 model = dict( from_pretrained="./ckpts/Open_Sora_v2_Video_DC_AE.safetensors", in_channels=128, cond_embed=True, patch_size=1, ) # AE settin...
36
704
Open-Sora
configs/diffusion/inference/256px_tp.py
.py
_base_ = [ # inherit grammer from mmengine "256px.py", "plugins/tp.py", # use tensor parallel ]
5
106
Open-Sora
configs/diffusion/inference/plugins/t2i2v.py
.py
use_t2i2v = True # flux configurations img_flux = dict( type="flux", from_pretrained="./ckpts/flux1-dev.safetensors", guidance_embed=True, # model architecture in_channels=64, vec_in_dim=768, context_in_dim=4096, hidden_size=3072, mlp_ratio=4.0, num_heads=24, depth=19, d...
37
834
Open-Sora
configs/diffusion/inference/plugins/sp.py
.py
plugin = "hybrid" plugin_config = dict( tp_size=1, pp_size=1, sp_size=8, sequence_parallelism_mode="ring_attn", enable_sequence_parallelism=True, static_graph=True, zero_stage=2, overlap_allgather=False, ) plugin_ae = "hybrid" plugin_config_ae = dict( tp_size=8, pp_size=1, s...
21
379
Open-Sora
configs/diffusion/inference/plugins/tp.py
.py
plugin = "hybrid" plugin_config = dict( tp_size=8, pp_size=1, sp_size=1, zero_stage=2, overlap_allgather=False, ) plugin_ae = "hybrid" plugin_config_ae = dict( tp_size=8, pp_size=1, sp_size=1, zero_stage=2, overlap_allgather=False, )
18
275
Open-Sora
configs/vae/train/video_dc_ae.py
.py
# ============ # model config # ============ model = dict( type="dc_ae", model_name="dc-ae-f32t4c128", from_scratch=True, from_pretrained=None, ) # ============ # data config # ============ dataset = dict( type="video_text", transform_name="resize_crop", data_path="datasets/pexels_45k_nec...
75
1,296
Open-Sora
configs/vae/train/video_dc_ae_disc.py
.py
_base_ = ["video_dc_ae.py"] discriminator = dict( type="N_Layer_discriminator_3D", from_pretrained=None, input_nc=3, n_layers=5, conv_cls="conv3d" ) disc_lr_scheduler = dict(warmup_steps=0) gen_loss_config = dict( gen_start=0, disc_weight=0.05, ) disc_loss_config = dict( disc_start=0,...
35
616
Open-Sora
configs/vae/inference/video_dc_ae.py
.py
dtype = "bf16" batch_size = 1 seed = 42 dataset = dict( type="video_text", transform_name="resize_crop", fps_max=16, data_path="datasets/pexels_45k_necessary.csv", ) bucket_config = { "512px_ar1:1": {96: (1.0, 1)}, } model = dict( type="dc_ae", model_name="dc-ae-f32t4c128", from_pretra...
33
632
Open-Sora
configs/vae/inference/hunyuanvideo_vae.py
.py
dtype = "bf16" batch_size = 1 seed = 42 save_dir = "samples/hunyuanvideo_vae" plugin = "zero2" dataset = dict( type="video_text", transform_name="resize_crop", fps_max=16, data_path="datasets/pexels_45k_necessary.csv", ) bucket_config = { "512px_ar1:1": {97: (1.0, 1)}, } num_workers = 24 num_bucke...
34
680
llama3
setup.py
.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. from setuptools import find_packages, setup def get_requirements(path: str): return [l.strip() for l in open(path)] setup( name="llama3",...
17
433
llama3
example_chat_completion.py
.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. from typing import List, Optional import fire from llama import Dialog, Llama def main( ckpt_dir: str, tokenizer_path: str, temperatu...
85
3,276
llama3
example_text_completion.py
.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. from typing import List import fire from llama import Llama def main( ckpt_dir: str, tokenizer_path: str, temperature: float = 0.6, ...
65
1,959
llama3
llama/model.py
.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. import math from dataclasses import dataclass from typing import Optional, Tuple import fairscale.nn.model_parallel.initialize as fs_init import tor...
303
10,404
llama3
llama/generation.py
.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. import json import os import sys import time from pathlib import Path from typing import List, Optional, Tuple, TypedDict import torch import torch....
366
15,393
llama3
llama/test_tokenizer.py
.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. import os from unittest import TestCase from llama.tokenizer import ChatFormat, Tokenizer # TOKENIZER_PATH=<path> python -m unittest llama/test_toke...
89
2,871
llama3
llama/tokenizer.py
.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. import os from logging import getLogger from pathlib import Path from typing import ( AbstractSet, cast, Collection, Dict, Iterat...
230
7,712
gpt-researcher
json_schema_generator.py
.py
import json from typing import Dict, Any from pydantic import BaseModel class UserSchema(BaseModel): id: int name: str email: str age: int is_active: bool def generate_structured_json(schema: BaseModel, data: Dict[str, Any]) -> str: """ Generate structured JSON output based on provided sch...
44
1,139
gpt-researcher
main.py
.py
from dotenv import load_dotenv import logging from pathlib import Path # Create logs directory if it doesn't exist logs_dir = Path("logs") logs_dir.mkdir(exist_ok=True) # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ ...
38
973
gpt-researcher
setup.py
.py
from setuptools import find_packages, setup LATEST_VERSION = "0.14.7" exclude_packages = [ "selenium", "webdriver", "fastapi", "fastapi.*", "uvicorn", "jinja2", "gpt-researcher", "langgraph" ] with open(r"README.md", "r", encoding="utf-8") as f: long_description = f.read() with o...
48
1,452
gpt-researcher
cli.py
.py
""" Provides a command line interface for the GPTResearcher class. Usage: ```shell python cli.py "<query>" --report_type <report_type> --tone <tone> --query_domains <foo.com,bar.com> ``` """ import argparse import asyncio import re from argparse import RawTextHelpFormatter from datetime import datetime from pathlib ...
363
12,555
gpt-researcher
docs/docs/examples/custom_prompt.py
.py
""" Custom Prompt Example for GPT Researcher This example demonstrates how to use the custom_prompt parameter to customize report generation based on specific formatting requirements or content needs. """ import asyncio import nest_asyncio # Required for notebooks/interactive environments # Apply nest_asyncio to al...
74
3,111
gpt-researcher
docs/docs/examples/sample_report.py
.py
import nest_asyncio # required for notebooks nest_asyncio.apply() from gpt_researcher import GPTResearcher import asyncio async def get_report(query: str, report_type: str, custom_prompt: str = None): researcher = GPTResearcher(query, report_type) research_result = await researcher.conduct_research() ...
47
1,577
gpt-researcher
docs/docs/examples/sample_sources_only.py
.py
from gpt_researcher import GPTResearcher import asyncio async def get_report(query: str, report_source: str, sources: list) -> str: researcher = GPTResearcher(query=query, report_source=report_source, source_urls=sources) research_context = await researcher.conduct_research() return await researcher.write...
21
786
gpt-researcher
tests/vector-store.py
.py
import asyncio import pytest from typing import List from gpt_researcher import GPTResearcher from langchain.text_splitter import CharacterTextSplitter from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import FAISS, InMemoryVectorStore from langchain_core.documents import Document #...
237
15,727
gpt-researcher
tests/test_openalex_malformed_results.py
.py
import importlib.util import sys import types import unittest from pathlib import Path from unittest.mock import MagicMock ROOT = Path(__file__).resolve().parents[1] MODULE_PATH = ROOT / "gpt_researcher" / "retrievers" / "openalex" / "openalex.py" def _load(): requests_mod = types.ModuleType("requests") cla...
74
2,482
gpt-researcher
tests/test_multi_agents_fact_revisions.py
.py
import importlib.util from pathlib import Path import pytest PATH = Path(__file__).resolve().parents[1] / "multi_agents" / "agents" / "fact_review.py" spec = importlib.util.spec_from_file_location("fact_review", PATH) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) def test_accept_none_notes...
28
842
gpt-researcher
tests/test_semantic_scholar_retriever.py
.py
"""Guards for Semantic Scholar malformed payloads / openAccessPdf shapes.""" from unittest.mock import MagicMock, patch from gpt_researcher.retrievers.semantic_scholar.semantic_scholar import ( SemanticScholarSearch, ) def _resp(payload): r = MagicMock() r.raise_for_status = MagicMock() r.json.retur...
64
1,649
gpt-researcher
tests/test_serper_returns_list.py
.py
"""Regression test: SerperSearch.search must always return a list, never None. Sibling retrievers (serpapi/brave/bing/searx) return [] on error; callers (`get_search_results` -> `len(search_results)`) crash on None. """ import sys import types from unittest.mock import patch # serper.py only imports os, requests, js...
63
1,598
gpt-researcher
tests/test_azure_document_loader.py
.py
import importlib.util import sys import types import unittest from pathlib import Path class _FakeBlobServiceClient: @classmethod def from_connection_string(cls, connection_string): return cls() def get_container_client(self, container_name): return None azure_module = types.ModuleType(...
88
2,653
gpt-researcher
tests/test_brave_retriever.py
.py
import os import unittest from unittest.mock import MagicMock, patch from gpt_researcher.retrievers.brave.brave import BraveSearch class TestBraveSearch(unittest.TestCase): def test_missing_api_key_raises_clear_error(self): with patch.dict(os.environ, {}, clear=True): with self.assertRaisesRe...
67
2,124