Spaces:
Paused
Paused
Update app.py
Browse files12345678910111213141516171819202122232425262728293011 unmodified lines4243444546474833 unmodified lines82838485868788899030 unmodified lines1211221231241251261271 unmodified line12913013113213313413511 unmodified lines14714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617751 unmodified lines22923023123223323423580 unmodified lines3163173183193203213223232 unmodified lines326327328329330331332333334335336337338339340341342343344345346347348349350351352353import osimport gcimport shutilimport torchimport torch.nn as nnimport numpy as npimport imageiofrom typing import *from easydict import EasyDict as edictfrom PIL import Image# [핵심 1] 메모리 파편화 방지 및 4090/L40S 등 최신 GPU 호환성 설정os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"os.environ['SPCONV_ALGO'] = 'native'import gradio as grfrom gradio_litmodel3d import LitModel3Dfrom trellis.pipelines import TrellisVGGTTo3DPipelinefrom trellis.representations import Gaussian, MeshExtractResultfrom trellis.utils import render_utils, postprocessing_utils# [핵심 2] Accelerate 라이브러리 필수 로드 (없으면 에러 발생)try:from accelerate import dispatch_model, infer_auto_device_mapfrom accelerate.utils import get_balanced_memoryexcept ImportError:raise ImportError("Accelerate library is missing. Please run `pip install accelerate`.")MAX_SEED = np.iinfo(np.int32).maxTMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')11 unmodified linestorch.cuda.empty_cache()def preprocess_image(image: Image.Image) -> Image.Image:# 파이프라인이 분산되어 있어도 전처리는 CPU/GPU0에서 수행됨processed_image = pipeline.preprocess_image(image)return processed_image33 unmodified lines}def unpack_state(state: dict) -> Tuple[Gaussian, edict, str]:# 결과물 렌더링 시에는 GPU 하나(보통 0번)나 CPU로 모아야 함device = 'cuda:0' if torch.cuda.is_available() else 'cpu'gs = Gaussian(aabb=state['gaussian']['aabb'],sh_degree=state['gaussian']['sh_degree'],30 unmodified linesreq: gr.Request,) -> Tuple[dict, str, str, str]:# [핵심 3] 실행 전 가비지 컬렉션으로 VRAM 확보gc.collect()torch.cuda.empty_cache()1 unmodified lineimage_files = [image[0] for image in multiimages]try:# [핵심 4] 추론 모드 강제. Gradient 저장 안 함 (메모리 절약)with torch.no_grad():outputs, _, _ = pipeline.run(image=image_files,11 unmodified linesmode=multiimage_algo,)except Exception as e:# 에러 발생 시 메모리 비우고 에러 다시 던짐torch.cuda.empty_cache()raise e# Render video (후처리는 단일 GPU 혹은 CPU에서 수행)# 텐서들이 여러 GPU에 흩어져 있을 수 있으므로 .cpu() 혹은 단일 cuda로 모아야 함# render_utils 내부에서 처리하겠지만 안전하게 진행video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]video_path = os.path.join(user_dir, 'sample.mp4')imageio.mimsave(video_path, video, fps=15)# Extract GLBgs = outputs['gaussian'][0]mesh = outputs['mesh'][0]glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)glb_path = os.path.join(user_dir, 'sample.glb')glb.export(glb_path)# Pack statestate = pack_state(gs, mesh)# 결과물 반환 후 메모리 정리del outputs, gs, mesh, glbgc.collect()torch.cuda.empty_cache()51 unmodified lines)with demo:gr.Markdown("""# 💻 ReconViaGen (Multi-GPU Force Enabled)""")with gr.Row():80 unmodified lines# Launch Scriptif __name__ == "__main__":print("🚀 Initializing Pipeline...")# [핵심 5] 모델 로딩 시점에 device를 지정하지 않고, CPU에 둡니다.# 이렇게 해야 accelerate가 '빈 모델' 상태 혹은 CPU 상태에서 가져가서 쪼갤 수 있습니다.pipeline = TrellisVGGTTo3DPipeline.from_pretrained("esther11/trellis-vggt-v0-2")gpu_count = torch.cuda.device_count()2 unmodified linesif gpu_count > 1:print("⚡ Multi-GPU Mode Activated: Distributing model across all available GPUs.")# [핵심 6] VGGT 모델 분산 (가장 큰 메모리 차지)# device_map="balanced"는 가능한 한 GPU 메모리를 고르게 쓰려고 노력합니다.# "auto"는 첫 번째 GPU부터 채우므로 OOM 위험이 있을 수 있어 balanced가 안전합니다.pipeline.VGGT_model = dispatch_model(pipeline.VGGT_model,device_map="balanced")# [핵심 7] SLAT 모델 분산 (그 다음으로 큼)pipeline.slat_model = dispatch_model(pipeline.slat_model,device_map="balanced")# [핵심 8] 나머지 가벼운 모델들은 GPU 0에 할당 (분산 오버헤드 방지)pipeline.birefnet_model.to("cuda:0")print("✅ Model dispatched successfully via Accelerate.")else:# 단일 GPU이거나 GPU가 없는 경우 (사용자가 원치 않지만 안전망으로 둠)print("⚠️ Warning: Only 1 GPU detected. Loading entire model to CUDA:0 (High OOM Risk).")pipeline.cuda()demo.launch()12345678910111213141516171819202122232425262728293031323334353611 unmodified lines48495051525333 unmodified lines8788899091929330 unmodified lines1241251261271281291 unmodified line13113213313413513611 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917051 unmodified lines22222322422522622722880 unmodified lines3093103113123133142 unmodified lines317318319320321322323324325326327328329330331332333334335336337338import osimport sysimport subprocess# [AUTO-INSTALL] accelerate 라이브러리 자동 설치try:import accelerateexcept ImportError:print("⚠️ accelerate not found. Installing now...")subprocess.check_call([sys.executable, "-m", "pip", "install", "accelerate"])print("✅ accelerate installed.")# [중요] OOM 방지 설정os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"os.environ['SPCONV_ALGO'] = 'native'import gradio as grfrom gradio_litmodel3d import LitModel3Dimport shutilfrom typing import *import torchimport torch.nn as nnimport numpy as npimport imageioimport gcfrom easydict import EasyDict as edictfrom PIL import Imagefrom trellis.pipelines import TrellisVGGTTo3DPipelinefrom trellis.representations import Gaussian, MeshExtractResultfrom trellis.utils import render_utils, postprocessing_utils# accelerate 로드 (위에서 설치했으므로 통과됨)from accelerate import dispatch_modelMAX_SEED = np.iinfo(np.int32).maxTMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')11 unmodified linestorch.cuda.empty_cache()def preprocess_image(image: Image.Image) -> Image.Image:processed_image = pipeline.preprocess_image(image)return processed_image33 unmodified lines}def unpack_state(state: dict) -> Tuple[Gaussian, edict, str]:device = 'cuda:0' if torch.cuda.is_available() else 'cpu'gs = Gaussian(aabb=state['gaussian']['aabb'],sh_degree=state['gaussian']['sh_degree'],30 unmodified linesreq: gr.Request,) -> Tuple[dict, str, str, str]:gc.collect()torch.cuda.empty_cache()1 unmodified lineimage_files = [image[0] for image in multiimages]try:with torch.no_grad():outputs, _, _ = pipeline.run(image=image_files,11 unmodified linesmode=multiimage_algo,)except Exception as e:torch.cuda.empty_cache()raise evideo = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]video_path = os.path.join(user_dir, 'sample.mp4')imageio.mimsave(video_path, video, fps=15)gs = outputs['gaussian'][0]mesh = outputs['mesh'][0]glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)glb_path = os.path.join(user_dir, 'sample.glb')glb.export(glb_path)state = pack_state(gs, mesh)del outputs, gs, mesh, glbgc.collect()torch.cuda.empty_cache()51 unmodified lines)with demo:gr.Markdown("""# 💻 ReconViaGen (Multi-GPU Auto-Install)""")with gr.Row():80 unmodified lines# Launch Scriptif __name__ == "__main__":print("🚀 Initializing Pipeline...")pipeline = TrellisVGGTTo3DPipeline.from_pretrained("esther11/trellis-vggt-v0-2")gpu_count = torch.cuda.device_count()2 unmodified linesif gpu_count > 1:print("⚡ Multi-GPU Mode Activated: Distributing model across all available GPUs.")pipeline.VGGT_model = dispatch_model(pipeline.VGGT_model,device_map="balanced")pipeline.slat_model = dispatch_model(pipeline.slat_model,device_map="balanced")pipeline.birefnet_model.to("cuda:0")print("✅ Model dispatched successfully via Accelerate.")else:print("⚠️ Warning: Only 1 GPU detected.")pipeline.cuda()demo.launch()
app.py+23-38