Run this model with HF Jobs
Run SumantBobade/Image_To_3D_Generator on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/SumantBobade/Image_To_3D_Generator. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/SumantBobade/Image_To_3D_Generator on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use SumantBobade/Image_To_3D_Generator with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use SumantBobade/Image_To_3D_Generator with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("SumantBobade/Image_To_3D_Generator", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
further clean!
Browse filesFiles changed (3)
- main.py+2-2
- mvdream/attention.py+13-85
- mvdream/models.py+12-176
4 unmodified lines567891011124 unmodified linesfrom mvdream.pipeline_mvdream import MVDreamStableDiffusionPipelinepipe = MVDreamStableDiffusionPipeline.from_pretrained(# "./weights", # local weights"ashawkey/mvdream-sd2.1-diffusers",torch_dtype=torch.float16)pipe = pipe.to("cuda")4 unmodified lines567891011124 unmodified linesfrom mvdream.pipeline_mvdream import MVDreamStableDiffusionPipelinepipe = MVDreamStableDiffusionPipeline.from_pretrained("./weights", # local weights# "ashawkey/mvdream-sd2.1-diffusers",torch_dtype=torch.float16)pipe = pipe.to("cuda")
1 unmodified line234567891011121314159 unmodified lines2526272829303132333435363738394041424344454647484950515223 unmodified lines76777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014125 unmodified lines1671681691701711721731741756 unmodified lines182183184185186187188137 unmodified lines32632732832933033133277 unmodified lines4104114124134144154162 unmodified lines4194204214224234244251 unmodified lineimport mathimport torchimport torch.nn.functional as Ffrom inspect import isfunctionfrom torch import nn, einsumfrom torch.amp.autocast_mode import autocastfrom einops import rearrange, repeatfrom typing import Optional, Anyfrom .util import checkpointtry:import xformers # type: ignore9 unmodified lines_ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32")def uniq(arr):return {el: True for el in arr}.keys()def default(val, d):if val is not None:return valreturn d() if isfunction(d) else ddef max_neg_value(t):return -torch.finfo(t.dtype).maxdef init_(tensor):dim = tensor.shape[-1]std = 1 / math.sqrt(dim)tensor.uniform_(-std, std)return tensor# feedforwardclass GEGLU(nn.Module):def __init__(self, dim_in, dim_out):super().__init__()23 unmodified linesreturn self.net(x)def zero_module(module):"""Zero out the parameters of a module and return it."""for p in module.parameters():p.detach().zero_()return moduledef Normalize(in_channels):return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)class SpatialSelfAttention(nn.Module):def __init__(self, in_channels):super().__init__()self.in_channels = in_channelsself.norm = Normalize(in_channels)self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)def forward(self, x):h_ = xh_ = self.norm(h_)q = self.q(h_)k = self.k(h_)v = self.v(h_)# compute attentionb, c, h, w = q.shapeq = rearrange(q, "b c h w -> b (h w) c")k = rearrange(k, "b c h w -> b c (h w)")w_ = torch.einsum("bij,bjk->bik", q, k)w_ = w_ * (int(c) ** (-0.5))w_ = torch.nn.functional.softmax(w_, dim=2)# attend to valuesv = rearrange(v, "b c h w -> b c (h w)")w_ = rearrange(w_, "b i j -> b j i")h_ = torch.einsum("bij,bjk->bik", v, w_)h_ = rearrange(h_, "b c (h w) -> b c h w", h=h)h_ = self.proj_out(h_)return x + h_class CrossAttention(nn.Module):def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):super().__init__()25 unmodified linesif _ATTN_PRECISION == "fp32":with autocast(enabled=False, device_type="cuda"):q, k = q.float(), k.float()sim = einsum("b i d, b j d -> b i j", q, k) * self.scaleelse:sim = einsum("b i d, b j d -> b i j", q, k) * self.scaledel q, k6 unmodified lines# attention, what we cannot get enough ofsim = sim.softmax(dim=-1)out = einsum("b i j, b j d -> b i d", sim, v)out = rearrange(out, "(b h) n d -> b n (h d)", h=h)return self.to_out(out)137 unmodified linescontext_dim = [context_dim]self.in_channels = in_channelsinner_dim = n_heads * d_headself.norm = Normalize(in_channels)if not use_linear:self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=077 unmodified linesdropout=0.0,context_dim=None,disable_self_attn=False,use_linear=False,use_checkpoint=True,):super().__init__()2 unmodified linescontext_dim = [context_dim]self.in_channels = in_channelsinner_dim = n_heads * d_headself.norm = Normalize(in_channels)if not use_linear:self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=01 unmodified line234567891011121314159 unmodified lines25262728293031323334353623 unmodified lines60616263646525 unmodified lines9192939495969798996 unmodified lines106107108109110111112137 unmodified lines25025125225325425525625725877 unmodified lines3363373383393403413422 unmodified lines3453463473483493503513523531 unmodified lineimport mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.amp.autocast_mode import autocastfrom inspect import isfunctionfrom einops import rearrange, repeatfrom typing import Optional, Anyfrom .util import checkpoint, zero_moduletry:import xformers # type: ignore9 unmodified lines_ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32")def default(val, d):if val is not None:return valreturn d() if isfunction(d) else dclass GEGLU(nn.Module):def __init__(self, dim_in, dim_out):super().__init__()23 unmodified linesreturn self.net(x)class CrossAttention(nn.Module):def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):super().__init__()25 unmodified linesif _ATTN_PRECISION == "fp32":with autocast(enabled=False, device_type="cuda"):q, k = q.float(), k.float()sim = torch.einsum("b i d, b j d -> b i j", q, k) * self.scaleelse:sim = torch.einsum("b i d, b j d -> b i j", q, k) * self.scaledel q, k6 unmodified lines# attention, what we cannot get enough ofsim = sim.softmax(dim=-1)out = torch.einsum("b i j, b j d -> b i d", sim, v)out = rearrange(out, "(b h) n d -> b n (h d)", h=h)return self.to_out(out)137 unmodified linescontext_dim = [context_dim]self.in_channels = in_channelsinner_dim = n_heads * d_headself.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)if not use_linear:self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=077 unmodified linesdropout=0.0,context_dim=None,disable_self_attn=False,use_linear=True,use_checkpoint=True,):super().__init__()2 unmodified linescontext_dim = [context_dim]self.in_channels = in_channelsinner_dim = n_heads * d_headself.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)if not use_linear:self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0
12345678214 unmodified lines2232242252262272282292 unmodified lines23223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234344 unmodified lines388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421113 unmodified lines5355365375385395405415425435445455465471 unmodified line54955055155255355455555655755855956056156256356456556656756856957030 unmodified lines6016026036046056066076086093 unmodified lines61361461561661761861962062162262362462562662762862963063163263363463563627 unmodified lines6646656666676686696706716726736746756761 unmodified line67867968068168268368468568668768868969069169269369469569669769869977 unmodified lines777778779780781782783# obtained and modified from https://github.com/bytedance/MVDreamimport mathimport numpy as npimport torch as thimport torch.nn as nnimport torch.nn.functional as Ffrom diffusers.configuration_utils import ConfigMixin214 unmodified linesemb_out = emb_out[..., None]if self.use_scale_shift_norm:out_norm, out_rest = self.out_layers[0], self.out_layers[1:]scale, shift = th.chunk(emb_out, 2, dim=1)h = out_norm(h) * (1 + scale) + shifth = out_rest(h)else:2 unmodified linesreturn self.skip_connection(x) + hclass AttentionBlock(nn.Module):"""An attention block that allows spatial positions to attend to each other.Originally ported from here, but adapted to the N-d case.https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66."""def __init__(self,channels,num_heads=1,num_head_channels=-1,use_checkpoint=False,use_new_attention_order=False,):super().__init__()self.channels = channelsif num_head_channels == -1:self.num_heads = num_headselse:assert (channels % num_head_channels == 0), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"self.num_heads = channels // num_head_channelsself.use_checkpoint = use_checkpointself.norm = nn.GroupNorm(32, channels)self.qkv = conv_nd(1, channels, channels * 3, 1)if use_new_attention_order:# split qkv before split headsself.attention = QKVAttention(self.num_heads)else:# split heads before split qkvself.attention = QKVAttentionLegacy(self.num_heads)self.proj_out = zero_module(conv_nd(1, channels, channels, 1))def forward(self, x):return checkpoint(self._forward, (x,), self.parameters(), True)def _forward(self, x):b, c, *spatial = x.shapex = x.reshape(b, c, -1)qkv = self.qkv(self.norm(x))h = self.attention(qkv)h = self.proj_out(h)return (x + h).reshape(b, c, *spatial)class QKVAttentionLegacy(nn.Module):"""A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping"""def __init__(self, n_heads):super().__init__()self.n_heads = n_headsdef forward(self, qkv):"""Apply QKV attention.:param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.:return: an [N x (H * C) x T] tensor after attention."""bs, width, length = qkv.shapeassert width % (3 * self.n_heads) == 0ch = width // (3 * self.n_heads)q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)scale = 1 / math.sqrt(math.sqrt(ch))weight = th.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwardsweight = th.softmax(weight.float(), dim=-1).type(weight.dtype)a = th.einsum("bts,bcs->bct", weight, v)return a.reshape(bs, -1, length)class QKVAttention(nn.Module):"""A module which performs QKV attention and splits in a different order."""def __init__(self, n_heads):super().__init__()self.n_heads = n_headsdef forward(self, qkv):"""Apply QKV attention.:param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.:return: an [N x (H * C) x T] tensor after attention."""bs, width, length = qkv.shapeassert width % (3 * self.n_heads) == 0ch = width // (3 * self.n_heads)q, k, v = qkv.chunk(3, dim=1)scale = 1 / math.sqrt(math.sqrt(ch))weight = th.einsum("bct,bcs->bts",(q * scale).view(bs * self.n_heads, ch, length),(k * scale).view(bs * self.n_heads, ch, length),) # More stable with f16 than dividing afterwardsweight = th.softmax(weight.float(), dim=-1).type(weight.dtype)a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))return a.reshape(bs, -1, length)class MultiViewUNetModel(ModelMixin, ConfigMixin):"""The full multi-view UNet model with attention, timestep embedding and camera embedding.44 unmodified linesnum_heads_upsample=-1,use_scale_shift_norm=False,resblock_updown=False,use_new_attention_order=False,use_spatial_transformer=False, # custom transformer supporttransformer_depth=1, # custom transformer supportcontext_dim=None, # custom transformer supportn_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq modellegacy=True,disable_self_attentions=None,num_attention_blocks=None,disable_middle_self_attn=False,use_linear_in_transformer=False,adm_in_channels=None,camera_dim=None,):super().__init__()if use_spatial_transformer:assert (context_dim is not None), "Fool!! You forgot to include the dimension of your cross-attention conditioning..."if context_dim is not None:assert (use_spatial_transformer), "Fool!! You forgot to use the spatial transformer for your cross-attention conditioning..."from omegaconf.listconfig import ListConfigif type(context_dim) == ListConfig:context_dim = list(context_dim)if num_heads_upsample == -1:num_heads_upsample = num_heads113 unmodified lineselse:num_heads = ch // num_head_channelsdim_head = num_head_channelsif legacy:# num_heads = 1dim_head = (ch // num_headsif use_spatial_transformerelse num_head_channels)if disable_self_attentions is not None:disabled_sa = disable_self_attentions[level]else:1 unmodified lineif num_attention_blocks is None or nr < num_attention_blocks[level]:layers.append(AttentionBlock(ch,use_checkpoint=use_checkpoint,num_heads=num_heads,num_head_channels=dim_head,use_new_attention_order=use_new_attention_order,)if not use_spatial_transformerelse SpatialTransformer3D(ch,num_heads,dim_head,depth=transformer_depth,context_dim=context_dim,disable_self_attn=disabled_sa,use_linear=use_linear_in_transformer,use_checkpoint=use_checkpoint,))30 unmodified lineselse:num_heads = ch // num_head_channelsdim_head = num_head_channelsif legacy:# num_heads = 1dim_head = ch // num_heads if use_spatial_transformer else num_head_channelsself.middle_block = TimestepEmbedSequential(ResBlock(ch,3 unmodified linesuse_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,),AttentionBlock(ch,use_checkpoint=use_checkpoint,num_heads=num_heads,num_head_channels=dim_head,use_new_attention_order=use_new_attention_order,)if not use_spatial_transformerelse SpatialTransformer3D(ch,num_heads,dim_head,depth=transformer_depth,context_dim=context_dim,disable_self_attn=disable_middle_self_attn,use_linear=use_linear_in_transformer,use_checkpoint=use_checkpoint,), # always uses a self-attnResBlock(ch,time_embed_dim,27 unmodified lineselse:num_heads = ch // num_head_channelsdim_head = num_head_channelsif legacy:# num_heads = 1dim_head = (ch // num_headsif use_spatial_transformerelse num_head_channels)if disable_self_attentions is not None:disabled_sa = disable_self_attentions[level]else:1 unmodified lineif num_attention_blocks is None or i < num_attention_blocks[level]:layers.append(AttentionBlock(ch,use_checkpoint=use_checkpoint,num_heads=num_heads_upsample,num_head_channels=dim_head,use_new_attention_order=use_new_attention_order,)if not use_spatial_transformerelse SpatialTransformer3D(ch,num_heads,dim_head,depth=transformer_depth,context_dim=context_dim,disable_self_attn=disabled_sa,use_linear=use_linear_in_transformer,use_checkpoint=use_checkpoint,))77 unmodified lineshs.append(h)h = self.middle_block(h, emb, context, num_frames=num_frames)for module in self.output_blocks:h = th.cat([h, hs.pop()], dim=1)h = module(h, emb, context, num_frames=num_frames)h = h.type(x.dtype)if self.predict_codebook_ids:1234567214 unmodified lines2222232242252262272282 unmodified lines23123223323423523644 unmodified lines281282283284285286287288289290291292293294295296297298113 unmodified lines4124134144154164174181 unmodified line42042142242342442542642742842943043143230 unmodified lines4634644654664674684693 unmodified lines47347447547647747847948048148248348448548648727 unmodified lines5155165175185195205211 unmodified line52352452552652752852953053153253353453577 unmodified lines613614615616617618619# obtained and modified from https://github.com/bytedance/MVDreamimport mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom diffusers.configuration_utils import ConfigMixin214 unmodified linesemb_out = emb_out[..., None]if self.use_scale_shift_norm:out_norm, out_rest = self.out_layers[0], self.out_layers[1:]scale, shift = torch.chunk(emb_out, 2, dim=1)h = out_norm(h) * (1 + scale) + shifth = out_rest(h)else:2 unmodified linesreturn self.skip_connection(x) + hclass MultiViewUNetModel(ModelMixin, ConfigMixin):"""The full multi-view UNet model with attention, timestep embedding and camera embedding.44 unmodified linesnum_heads_upsample=-1,use_scale_shift_norm=False,resblock_updown=False,transformer_depth=1, # custom transformer supportcontext_dim=None, # custom transformer supportn_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq modeldisable_self_attentions=None,num_attention_blocks=None,disable_middle_self_attn=False,adm_in_channels=None,camera_dim=None,):super().__init__()assert context_dim is not Noneif num_heads_upsample == -1:num_heads_upsample = num_heads113 unmodified lineselse:num_heads = ch // num_head_channelsdim_head = num_head_channelsif disable_self_attentions is not None:disabled_sa = disable_self_attentions[level]else:1 unmodified lineif num_attention_blocks is None or nr < num_attention_blocks[level]:layers.append(SpatialTransformer3D(ch,num_heads,dim_head,depth=transformer_depth,context_dim=context_dim,disable_self_attn=disabled_sa,use_checkpoint=use_checkpoint,))30 unmodified lineselse:num_heads = ch // num_head_channelsdim_head = num_head_channelsself.middle_block = TimestepEmbedSequential(ResBlock(ch,3 unmodified linesuse_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,),SpatialTransformer3D(ch,num_heads,dim_head,depth=transformer_depth,context_dim=context_dim,disable_self_attn=disable_middle_self_attn,use_checkpoint=use_checkpoint,),ResBlock(ch,time_embed_dim,27 unmodified lineselse:num_heads = ch // num_head_channelsdim_head = num_head_channelsif disable_self_attentions is not None:disabled_sa = disable_self_attentions[level]else:1 unmodified lineif num_attention_blocks is None or i < num_attention_blocks[level]:layers.append(SpatialTransformer3D(ch,num_heads,dim_head,depth=transformer_depth,context_dim=context_dim,disable_self_attn=disabled_sa,use_checkpoint=use_checkpoint,))77 unmodified lineshs.append(h)h = self.middle_block(h, emb, context, num_frames=num_frames)for module in self.output_blocks:h = torch.cat([h, hs.pop()], dim=1)h = module(h, emb, context, num_frames=num_frames)h = h.type(x.dtype)if self.predict_codebook_ids:
main.py+2-2
mvdream/attention.py+13-85
mvdream/models.py+12-176