Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Helios/_DEV/__pycache__/infer_helios.cpython-312.pyc +0 -0
- Helios/_DEV/demo_data/MovieGenVideoBench_extended.txt +0 -0
- Helios/_DEV/demo_data/VBench_extended.txt +0 -0
- Helios/_DEV/example/prompt.txt +11 -0
- Helios/_DEV/example/prompt_interactive_helios.csv +54 -0
- Helios/_DEV/example/toy_data/toy_filter.json +46 -0
- Helios/_DEV/helios/__init__.py +0 -0
- Helios/_DEV/helios/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV/helios/dataset/__init__.py +0 -0
- Helios/_DEV/helios/dataset/dataloader_dmd.py +531 -0
- Helios/_DEV/helios/dataset/dataloader_history_latents_dist.py +685 -0
- Helios/_DEV/helios/dataset/dataloader_mp4_dist.py +854 -0
- Helios/_DEV/helios/diffusers_version/__init__.py +0 -0
- Helios/_DEV/helios/diffusers_version/pipeline_helios_diffusers.py +1406 -0
- Helios/_DEV/helios/diffusers_version/scheduling_helios_diffusers.py +947 -0
- Helios/_DEV/helios/diffusers_version/transformer_helios_diffusers.py +825 -0
- Helios/_DEV/helios/modules/__init__.py +0 -0
- Helios/_DEV/helios/modules/transformer_helios.py +1913 -0
- Helios/_DEV/helios/pipelines/__init__.py +0 -0
- Helios/_DEV/helios/pipelines/pipeline_helios.py +1535 -0
- Helios/_DEV/helios/pipelines/pipeline_helios_ode.py +1510 -0
- Helios/_DEV/helios/pipelines/pipeline_output.py +22 -0
- Helios/_DEV/helios/scheduler/__init__.py +0 -0
- Helios/_DEV/helios/scheduler/scheduling_helios.py +1056 -0
- Helios/_DEV/helios/utils/create_ema_zero3.py +401 -0
- Helios/_DEV/helios/utils/create_ema_zero3_lora.py +336 -0
- Helios/_DEV/tools/merge_lora_for_helios.py +55 -0
- Helios/_DEV/tools/merge_lora_for_wan.py +55 -0
- Helios/_DEV/tools/remove_ckpt.sh +5 -0
- Helios/_DEV/tools/requirements_old.txt +42 -0
- Helios/_DEV/tools/requirements_raw.txt +539 -0
- Helios/demo_data/MovieGenVideoBench_extended.txt +0 -0
- Helios/demo_data/VBench_extended.txt +0 -0
- Helios/eval/0_get_aesthetic.py +203 -0
- Helios/eval/10_merge_all_results.py +152 -0
- Helios/eval/1_get_motion_amplitude.py +194 -0
- Helios/eval/2_get_motion_smoothness.py +301 -0
- Helios/eval/3_get_semantic.py +207 -0
- Helios/eval/4_get_naturalness.py +287 -0
- Helios/eval/5_get_drifting_aesthetic.py +239 -0
- Helios/eval/6_get_drifting_motion_smoothness.py +336 -0
- Helios/eval/7_get_drifting_semantic.py +268 -0
- Helios/eval/8_get_drifting_naturalness.py +339 -0
- Helios/eval/9_merge_all_scores.py +230 -0
- Helios/eval/README.md +167 -0
- Helios/eval/kill.sh +13 -0
- Helios/eval/requirements.txt +31 -0
- Helios/eval/run_metrics.sh +104 -0
- Helios/eval/run_metrics_ddp.sh +138 -0
- Helios/eval_moviebench/0_get_aesthetic.py +171 -0
Helios/_DEV/__pycache__/infer_helios.cpython-312.pyc
ADDED
|
Binary file (30.3 kB). View file
|
|
|
Helios/_DEV/demo_data/MovieGenVideoBench_extended.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/demo_data/VBench_extended.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/example/prompt.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement.
|
| 2 |
+
An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in thought pondering the history of the universe as he sits at a cafe in Paris, his eyes focus on people offscreen as they walk as he sits mostly motionless, he is dressed in a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses and has a very professorial appearance, and the end he offers a subtle closed-mouth smile as if he found the answer to the mystery of life, the lighting is very cinematic with the golden light and the Parisian streets and city in the background, depth of field, cinematic 35mm film.
|
| 3 |
+
A handheld tracking shot following a red balloon floating above the ground in an abandoned street. The balloon drifts gracefully, its bright red color contrasting sharply against the decaying urban backdrop. The street is littered with debris and graffiti-covered walls, with broken windows and rusted cars scattered about. Shadows dance across the scene as sunlight filters through gaps in the buildings. The camera moves fluidly, capturing the balloon's gentle ascent and descent, emphasizing its playful motion. A close-up of the balloon transitions to a wider shot, showcasing the desolate environment.
|
| 4 |
+
The camera follows behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by pine trees on a steep mountain slope, dust kicks up from it's tires, the sunlight shines on the SUV as it speeds along the dirt road, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other cars or vehicles in sight. The trees on either side of the road are redwoods, with patches of greenery scattered throughout. The car is seen from the rear following the curve with ease, making it seem as if it is on a rugged drive through the rugged terrain. The dirt road itself is surrounded by steep hills and mountains, with a clear blue sky above with wispy clouds.
|
| 5 |
+
A drone camera circles around a beautiful historic church built on a rocky outcropping along the Amalfi Coast, the view showcases historic and magnificent architectural details and tiered pathways and patios, waves are seen crashing against the rocks below as the view overlooks the horizon of the coastal waters and hilly landscapes of the Amalfi Coast Italy, several distant people are seen walking and enjoying vistas on patios of the dramatic ocean views, the warm glow of the afternoon sun creates a magical and romantic feeling to the scene, the view is stunning captured with beautiful photography.
|
| 6 |
+
A large orange octopus is seen resting on the bottom of the ocean floor, blending in with the sandy and rocky terrain. Its tentacles are spread out around its body, and its eyes are closed. The octopus is unaware of a king crab that is crawling towards it from behind a rock, its claws raised and ready to attack. The crab is brown and spiny, with long legs and antennae. The scene is captured from a wide angle, showing the vastness and depth of the ocean. The water is clear and blue, with rays of sunlight filtering through. The shot is sharp and crisp, with a high dynamic range. The octopus and the crab are in focus, while the background is slightly blurred, creating a depth of field effect.
|
| 7 |
+
A vibrant tropical fish glides gracefully through colorful ocean reefs, surrounded by swaying coral, shimmering schools of tiny fish, and beams of sunlight filtering down from the water’s surface. The scene feels alive with movement, as bubbles rise gently and the reef glows in vivid shades of blue, orange, and pink, creating a tranquil yet dynamic underwater atmosphere.
|
| 8 |
+
Cinematic closeup and detailed portrait of a reindeer in a snowy forest at sunset. The lighting is cinematic and gorgeous and soft and sun-kissed, with golden backlight and dreamy bokeh and lens flares. The color grade is cinematic and magical.
|
| 9 |
+
3D animation of a small, round, fluffy creature with big, expressive eyes explores a vibrant, enchanted forest. The creature, a whimsical blend of a rabbit and a squirrel, has soft blue fur and a bushy, striped tail. It hops along a sparkling stream, its eyes wide with wonder. The forest is alive with magical elements: flowers that glow and change colors, trees with leaves in shades of purple and silver, and small floating lights that resemble fireflies. The creature stops to interact playfully with a group of tiny, fairy-like beings dancing around a mushroom ring. The creature looks up in awe at a large, glowing tree that seems to be the heart of the forest.
|
| 10 |
+
A dynamic time-lapse video showing the rapidly moving scenery from the window of a speeding train. The camera captures various elements such as lush green fields, towering trees, quaint countryside houses, and distant mountain ranges passing by quickly. The train window frames the view, adding a sense of speed and motion as the landscape rushes past. The camera remains static but emphasizes the fast-paced movement outside. The overall atmosphere is serene yet exhilarating, capturing the essence of travel and exploration. Medium shot focusing on the train window and the rushing scenery beyond.
|
| 11 |
+
|
Helios/_DEV/example/prompt_interactive_helios.csv
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
id,prompt_index,prompt
|
| 2 |
+
6,0,"Underwater tornado affecting the ocean floor in a dramatic and chaotic scene. The water is murky, swirling violently, carrying debris and marine life into the vortex. Schools of fish scatter in panic, trying to avoid the powerful currents. Coral reefs and rocks are uprooted and tossed around, creating a tumultuous environment. In the background, large schools of fish swim away from the chaos, while smaller organisms cling to whatever they can find for safety. The camera remains stationary, capturing the intensity of the underwater tornado as it disrupts the serene ocean floor. Close-up shot emphasizing the turbulent motion and destruction."
|
| 3 |
+
6,1,"The underwater vortex intensifies its grip on the seabed, pulling a rusted, barnacle-encrusted anchor from the sand. The heavy iron object spins lethargically at first before being whipped upward into the murky funnel, smashing through floating debris with violent force. Sediment billows in thick clouds around the base of the tornado, obscuring the terrified marine life darting through the gloom. The chaotic currents tear at the ocean floor, exposing deeper layers of rock and silt as the destruction mounts. Close-up shot emphasizing the turbulent motion and destruction."
|
| 4 |
+
6,2,"The underwater tornado rages with unrelenting fury, now dislodging a massive, ancient shipwreck rib from the sediment. The curved wooden beam, blackened by time, groans silently as it is wrenched free and sucked into the spiraling column of water. Murky currents thrash wildly, tossing the heavy timber like a twig amidst the swirling sand and uprooted coral. Smaller debris clatters against the rotating wood, adding to the visual chaos of the deep-sea storm. The vortex dominates the frame, a terrifying engine of nature reshaping the seabed. Close-up shot emphasizing the turbulent motion and destruction."
|
| 5 |
+
6,3,"The violent vortex now ensnares a large, glowing jellyfish, dragging its long, bioluminescent tentacles into the chaotic spiral. The delicate creature spins helplessly, its translucent bell pulsing rapidly against the crushing force of the murky water. Swirling currents rip through the surrounding gloom, tossing sand and fragmented shells in every direction as the tornado dominates the seabed. The glowing blue light of the jellyfish streaks through the darkness, creating a ghostly blur within the churning debris field. Close-up shot emphasizing the turbulent motion and destruction."
|
| 6 |
+
6,4,"The swirling underwater vortex now seizes a heavy, encrusted treasure chest, its lid flapping open as it is torn from the ocean floor. Gold coins and silver trinkets spill out, glittering briefly in the murky water before being swept instantly into the violent funnel. The heavy wooden box tumbles end over end, colliding with floating rocks and adding to the debris field. Swirling sediment and bubbles surround the spilling fortune, highlighting the chaotic power of the storm as it ravages the seabed. Close-up shot emphasizing the turbulent motion and destruction."
|
| 7 |
+
6,5,"The violent underwater tornado continues its rampage, now ripping a massive, stone tiki statue from its resting place on the ocean floor. The carved face of the heavy idol spins wildly as it is sucked into the murky vortex, colliding with swirling rocks and sand. Debris crashes against the stone surface, chipping away at its ancient features while the chaotic currents drag it higher into the funnel. The surrounding water remains thick with sediment, obscuring the background as the heavy statue becomes another victim of the deep-sea storm. Close-up shot emphasizing the turbulent motion and destruction."
|
| 8 |
+
8,1,"A medium close-up of a serene, young East Asian woman with long pink hair, wearing a simple white gown that flows softly around her. She stands amidst gently falling sakura petals, which swirl around her, partially obscuring her figure in a dreamy, ethereal haze. Her delicate features are calm and tranquil as she gazes off into the distance. The background is blurred, featuring a soft pink and white sky with faint outlines of cherry blossom branches. The scene is bathed in a gentle, diffused light, creating a soft, dreamlike atmosphere."
|
| 9 |
+
8,2,"In a serene, still environment, a woman gently lifts her hand towards a delicate flower petal, her fingertips barely touching the wisps of smoke floating nearby. She has a soft, contemplative expression on her face, and her hand moves slowly and gracefully. The scene is captured from a medium close-up angle, focusing on her hand and the petal, with the subtle movement and interaction emphasized. The background is blurred, creating a gentle focus on the main action. The lighting is soft and diffused, adding to the tranquil atmosphere."
|
| 10 |
+
8,3,"A gentle breeze rustles through the air, causing cherry blossom petals to dance gracefully around a young woman's outstretched hand. She stands with a serene expression, wearing a traditional hanfu gown with flowing sleeves. The background showcases a tranquil garden with a winding path and blooming cherry trees. Soft sunlight filters through the leaves, casting dappled shadows on the ground. The scene is captured in a medium close-up, focusing on her hand and the swirling petals, with a slow pan to reveal the beautiful surroundings."
|
| 11 |
+
8,4,"A serene woman with closed eyes and soft, resting eyelashes, exuding a sense of tranquility and peace. She sits gracefully with her hands gently folded in her lap, wearing a flowing, pastel-colored dress that complements her calm demeanor. The lighting is soft and diffused, casting a gentle glow over her face. The background is a blurred, natural setting with hints of greenery and a tranquil atmosphere. The camera focuses closely on her face, capturing the subtle rise and fall of her breath as she maintains a peaceful composure. Close-up shot, emphasizing her serene expression and the gentle movement of her body."
|
| 12 |
+
8,5,"A serene nature scene where a young woman with flowing hair and a gentle expression steps forward gracefully on a grassy meadow. In the background, a small bird flutters and lands on a nearby tree branch. The woman's soft movements contrast with the bird's quick flight, creating a peaceful and harmonious atmosphere. The camera follows her as she moves, capturing the delicate interplay between the woman and the natural world in a medium close-up. The lighting is soft and natural, casting a warm glow over the scene."
|
| 13 |
+
8,6,"A serene moment captured in a magical realism style, where a graceful bird perches delicately on the outstretched finger of a woman. The bird has vibrant plumage and a calm demeanor. Pink and faint cyan-blue smoke begins to swirl and thicken around them, gently enveloping the scene in a soft, misty haze. The woman stands gracefully, her hand extended, with a serene expression. The background is a dimly lit, cozy room with warm wooden elements and soft lighting, adding to the enchanting atmosphere. Medium close-up shot focusing on the interaction between the woman and the bird, with the smoke swirling in the foreground."
|
| 14 |
+
11,1,"In a serene autumn clearing bathed in the warm, golden hues of late afternoon sunlight filtering through tall maple trees, a carpet of vibrant red and orange leaves blankets the ground. A rustic wooden footbridge arches gracefully over a gently trickling stream. Center frame, a sleek silver-gray house cat trots briskly across the leaf-strewn ground, its tail flicking energetically. As a cool breeze stirs, more leaves swirl and dance across the lens, adding a dynamic motion to the tranquil scene. Medium shot capturing the cat in motion against the backdrop of falling leaves."
|
| 15 |
+
11,2,"In a lush forest setting, a playful house cat bounds towards the treeline, leaping gracefully over a fallen log. Mid-stride, the cat transforms into a sleek, smoky brown wildcat with tufted ears and lean, powerful muscles. It continues to run swiftly through the drifting autumn leaves, propelled by its agility and strength. The camera follows the wildcat in a smooth tracking shot, capturing the dynamic motion and the rich, vibrant colors of the forest floor."
|
| 16 |
+
11,3,"In the warm golden hour, a wildcat leaps gracefully across a sparkling stream. As it runs, its body broadens and its fur transforms from its original color to a deep russet tone, morphing seamlessly into a sleek red fox. The fox's bushy, vibrant plume tail catches the sunlight, illuminating its swift movement as it dashes forward. The scene is captured from a dynamic tracking shot, emphasizing the fluid transition and the natural beauty of the changing landscape. Close-up and mid-shot transitions highlight the transformation and the glowing amber sky."
|
| 17 |
+
11,4,"In twilight, a red fox races across an old stone bridge, its chest heaving and coat gradually graying as it transforms into a majestic gray wolf mid-jump. The wolf then gallops through an open forest clearing, leaping over a babbling stream, and continues up the hillside. The sky transitions from orange to deep purple, with stars beginning to twinkle overhead. The camera follows the wolf's swift movement, starting from a medium shot on the bridge and zooming out to a wide-angle view of the wolf bounding towards the hillside under the fading light."
|
| 18 |
+
11,5,"In a serene moonlit forest, the transformation of a wolf into an antelope unfolds gracefully. Initially, the wolf's limbs elongate and refine, its fur shortening from its dense winter coat to a sleek, tawny color. As it shifts, small horns begin to emerge from its forehead. The antelope then swiftly bounds between trees, leaping over obstacles with ease, and finally clearing a tranquil stream in a single graceful leap. The camera captures this magical metamorphosis with smooth tracking shots and close-ups, emphasizing the fluidity and beauty of the change."
|
| 19 |
+
11,6,"In a mystical scene under the bright moonlight, an antelope gradually transforms into a powerful horse. Initially, the antelope has a slender frame with a rich chestnut coat. As the transformation progresses, it grows taller and heavier, developing the muscular build and sturdy legs of a horse. The horse then begins to gallop majestically towards the horizon, its mane flowing freely in the wind. Its hooves rhythmically ring against the leaf-strewn ground, seamlessly completing the metamorphosis from cat-like agility to equine power. The scene is captured in a sweeping aerial shot, emphasizing the fluidity and grace of the transformation."
|
| 20 |
+
14,1,"Close-up from the left side of a forest clearing, focus on a little girl in a light pink tulle dress with long flowing brown hair. She gazes slightly upward with a gentle, serene expression. The ground is covered in green grass and scattered wildflowers, with light mist creating an ethereal atmosphere. Sunbeams filter through the tall tree branches, casting dappled light. The scene is rendered in fantasy realism with soft, dreamy lighting, emphasizing the magical quality of the forest."
|
| 21 |
+
14,2,"A slow pullback reveals a glowing magical stone appearing on the right side of the frame. In the center, a young girl remains stationary, her expression serene and focused. Sunbeams filter through the clouds, shifting slightly as the camera moves backward, casting gentle shadows across the scene. The background gradually comes into view, showcasing a mystical forest with tall trees and vibrant greenery. The camera captures the magic and wonder of the moment in a medium-wide shot."
|
| 22 |
+
14,3,"Start with a close-up of a young boy in a blue robe adorned with a light tulle cloak as he enters from the right side of the frame. As he stops, the camera slowly pulls back to reveal a girl watching him intently from a few feet away. In the background, a large stone statue remains stationary, adding a sense of permanence and stillness to the scene. The environment is a dimly lit, ancient-looking room with stone walls and pillars. The camera movement emphasizes the interaction between the characters and their surroundings, capturing their expressions and body language clearly. Medium to wide shot transition."
|
| 23 |
+
14,4,"A slight pan and pullback reveal a young boy nodding his head, his face showing a mixture of curiosity and determination. In response, a young girl raises her hand in acknowledgment, her expression serene and focused. Both children stand near a luminous stone that continues to emit a soft, warm glow, casting gentle light over the surrounding area. The scene takes place in a dimly lit forest clearing, with tall trees and dense undergrowth visible in the background. Medium shot transitioning to wide shot."
|
| 24 |
+
14,5,"In a serene forest clearing, a young woman with flowing blonde hair turns towards a young man standing beside her. As the camera pulls to a medium shot, the couple's intimate moment is revealed against a backdrop of vibrant wildflowers and wisps of mist gently hovering above the ground. The environment is bathed in soft, natural light, enhancing the romantic atmosphere. The camera movement smoothly captures the subtle shift in their positions, bringing the entire scene into clear focus."
|
| 25 |
+
14,6,"Wide shot: A young boy in a casual outfit walks out to the right, while a girl stays stationary to the left. In the middle of a fully lit forest clearing, a luminous stone emits a warm glow, surrounded by drifting mist and soft sunbeams filtering through the canopy. The camera pans slowly to follow the boy as he moves, capturing the serene beauty of the misty landscape and the mystical ambiance created by the glowing stone."
|
| 26 |
+
20,0,"A majestic lion named Leo stands regally in the heart of a dense jungle, embodying the essence of a king. Leo has a golden mane that flows gracefully around his broad shoulders, and his piercing amber eyes survey the landscape with confidence and authority. He is positioned on a rocky outcrop, towering over the lush greenery below. The background showcases a vibrant jungle scene with tall trees, cascading vines, and dappled sunlight filtering through the canopy. Leo's posture is proud and commanding, with his tail held high. The scene is captured from a medium close-up perspective, emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 27 |
+
20,1,"Leo shifts his powerful weight slightly on the rocky outcrop, his golden mane rippling as he does so. Suddenly, he opens his massive jaws to release a deep, resonant roar that vibrates through the humid air, revealing his formidable white teeth. The dappled sunlight filtering through the canopy dances across his fur as his chest expands with the effort. The vibrant jungle remains lush and green around him, with tall trees and cascading vines framing his commanding figure. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 28 |
+
20,2,"Leo maintains his regal position on the rocky outcrop as the humid jungle air settles around his broad shoulders. He suddenly lowers his massive head to sniff a vibrant blue butterfly that has fluttered near his nose, his piercing amber eyes momentarily softening with curiosity. The dappled sunlight continues to filter through the tall trees and cascading vines, illuminating the golden hues of his mane against the lush green background. His tail remains held high, a symbol of his enduring authority over the landscape. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 29 |
+
20,3,"Leo stands tall on the rocky outcrop in the heart of the dense jungle, his golden mane glowing in the dappled sunlight. He lifts a massive paw to swipe gently at a low-hanging vine that dangles just within his reach, testing its texture with sharp claws. His piercing amber eyes remain alert, scanning the lush greenery and tall trees that surround him. The vibrant background of cascading vines and filtered light frames his regal form perfectly. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 30 |
+
20,4,"Leo remains on the rocky outcrop in the heart of the dense jungle, his golden mane catching the filtered light. He suddenly turns his head sharply to the left, his ears twitching as he focuses on a brightly colored parrot that lands on a nearby branch. His piercing amber eyes lock onto the bird with intense focus, analyzing the new arrival amidst the tall trees and cascading vines. The lush greenery provides a vibrant backdrop as he stands with authority, his posture commanding and proud. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 31 |
+
20,5,"Leo stands regally on the rocky outcrop in the heart of the dense jungle, his golden mane flowing around his broad shoulders. He dips his head low to lap cool water from a small, clear puddle that has formed in a crevice of the stone, his rough tongue splashing gently. His piercing amber eyes briefly close in satisfaction before reopening to survey the lush greenery, tall trees, and cascading vines. The dappled sunlight filters through the canopy, highlighting the wet fur on his muzzle. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 32 |
+
153,0,"90s VHS-style The Weather Channel scene, featuring a weatherman standing in front of a green screen with a large map of storm systems behind him. The weatherman, dressed in a casual but professional outfit, points emphatically at the rapidly moving storms on the map. His face shows concern and urgency as he speaks directly to the camera. The background map displays swirling patterns indicating severe weather conditions. The overall scene has a vintage, grainy texture with the characteristic noise and color palette of old VHS recordings. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 33 |
+
153,1,"The weatherman now reaches into his pocket and pulls out a chunky black walkie-talkie, pressing it against his ear with a sudden look of intense focus. He nods sharply while listening to an urgent update, his brow furrowing deeper under the studio lights. The green screen map behind him flickers slightly as the swirling storm systems intensify in color, shifting from red to deep purple. The vintage VHS grain distorts the edges of his suit jacket as he lowers the device and turns back to address the viewers with renewed alarm. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 34 |
+
153,2,"The weatherman suddenly unrolls a large, paper topographic map across a small stand that appears from the side, smoothing out the creases with frantic energy. He traces a specific mountain range with his finger, highlighting a dangerous path the storm is taking, his eyes wide with genuine fear. The digital map behind him glitches momentarily, syncing with his analogue demonstration as the VHS static rolls vertically across the frame. The studio lights reflect off the glossy paper surface as he taps a specific valley location repeatedly. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 35 |
+
153,3,"The weatherman abruptly grabs a bright red marker pen from the desk edge and begins circling a specific coastal city directly on the camera lens itself. He draws a jagged, erratic line across the glass to simulate the storm's unpredictable path, his hand shaking slightly with adrenaline. The ink squeaks audibly against the surface as the green screen map behind him pulses with warning icons. The VHS static buzzes louder, momentarily distorting his face as he caps the marker and stares intensely through his red drawings. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 36 |
+
153,4,"The weatherman now lifts a large, distinct ""Hurricane Warning"" sign made of heavy cardboard, holding it up beside his face for the audience to see clearly. The blocky red letters on the sign contrast sharply with his beige suit as he taps the edge of the board for emphasis. Behind him, the digital map swirls violently, the green screen effects blending slightly with the edges of the physical prop. The VHS tracking lines jitter horizontally across the bottom of the frame, enhancing the retro aesthetic as he maintains intense eye contact. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 37 |
+
153,5,"The weatherman suddenly dons a bright yellow rain slicker over his suit, struggling momentarily with the snaps as he prepares for a simulated outdoor report. He pulls the hood up over his head, framing his face tightly while the green screen behind him shifts to show footage of swaying palm trees and flying debris. The synthetic material of the coat reflects the studio lights with a harsh glare, adding to the chaotic atmosphere. The grainy VHS texture creates color bleeding around the vibrant yellow fabric as he shouts over imaginary wind. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 38 |
+
200,0,"A female astronaut in a full spacesuit, including an astronaut helmet, is running swiftly away from an unknown threat. She has a determined and focused expression on her face. The spacesuit is sleek, silver, and equipped with various gadgets and sensors. Her hair is visible under the helmet, flowing behind her as she runs. The background shows a desolate, rocky landscape with distant mountains and a dark, starry sky. The scene captures a medium shot of the woman mid-run, emphasizing her speed and urgency."
|
| 39 |
+
200,1,"The silver-suited astronaut sprints across the rocky terrain, but now she firmly clutches a glowing red geological scanner in her right hand, its lights pulsing rhythmically against the dark environment. Her expression remains intense under the helmet visor as she navigates the uneven ground, the sleek gadgets on her suit reflecting faint starlight. The desolate landscape stretches endlessly around her, framed by jagged mountains in the distance. The medium shot tracks alongside her movement, keeping pace with her urgent stride against the backdrop of the vast, starry void. medium shot mid-run speed urgency"
|
| 40 |
+
200,2,"The female astronaut races forward across the jagged terrain, her silver spacesuit gleaming against the dark void. Suddenly, a small drone detaches from her shoulder armor and hovers briefly before zooming ahead to scout the path. Her face remains locked in focused determination behind the helmet visor as her hair shifts with her rapid movement. The desolate rocky ground and looming distant mountains provide a stark backdrop to her flight. The camera maintains a medium shot of the woman mid-run, emphasizing her speed and urgency"
|
| 41 |
+
200,3,"The female astronaut sprints across the desolate, rocky landscape, her silver spacesuit reflecting the cold starlight. As she runs, she suddenly raises her left arm to activate a holographic map projected from her wrist gauntlet, displaying a complex grid of blue lines and waypoints. Her expression remains fierce and concentrated behind the helmet visor while her hair moves with the momentum of her stride. The dark mountains loom in the distance under the starry sky. The scene captures a medium shot of the woman mid-run, emphasizing her speed and urgency"
|
| 42 |
+
200,4,"The female astronaut dashes across the uneven, rocky ground, her sleek silver spacesuit shimmering under the starry sky. Without slowing her rapid pace, she reaches to her belt and deploys a luminous blue energy flare, dropping it behind her to mark her trail. Her face is set in a look of grim determination inside the helmet, with strands of hair floating with her motion. The dark, desolate landscape and distant mountains rush by as she flees. The scene captures a medium shot of the woman mid-run, emphasizing her speed and urgency"
|
| 43 |
+
200,5,"The silver-clad astronaut sprints relentlessly across the treacherous rocky terrain, her breath fogging the corner of her helmet visor. As she runs, she suddenly taps a control on her chest plate, causing a pair of bright white headlights to activate on either side of her helmet, cutting through the darkness ahead. Her determined eyes scan the illuminated path while the desolate landscape and jagged mountains blur in the background. The starry sky hangs heavy above her swift escape. The scene captures a medium shot of the woman mid-run, emphasizing her speed and urgency"
|
| 44 |
+
312,0,"A young woman standing in the rain, looking up at the sky with a warm, inviting smile on her face. She is dressed in a light, flowy dress that clings to her form as droplets of water fall around her. Her hair is gently tousled from the rain, framing her delicate features. The background shows a blurred cityscape with tall buildings and the faint glow of streetlights. The scene captures the serene beauty of a rainy evening. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 45 |
+
312,2,"The young woman remains framed against the soft blur of city lights, the rain now glistening on her skin as she slowly extends her right hand palm-up to catch the falling droplets. Her expression shifts slightly to one of quiet wonder as the water pools in her cupped fingers. The light fabric of her dress continues to sway subtly with the gentle wind, emphasizing the damp atmosphere. The distant streetlights create bokeh orbs behind her silhouette. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 46 |
+
312,3,"The young woman in the light, flowy dress now closes her eyes, tilting her head back slightly to let the rain wash over her face. She reaches into her pocket and pulls out a bright red origami crane, holding it delicately between her fingers. The paper quickly darkens as it absorbs the moisture, contrasting with the blurred gray cityscape behind her. Her hair is plastered more closely to her cheeks by the persistent downpour, while the streetlights cast a soft, shimmering glow on the wet paper bird. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 47 |
+
312,4,"The young woman in the soaked flowy dress opens her eyes and suddenly unfurls a small, transparent umbrella with a floral pattern above her head. The rain drums rhythmically against the plastic canopy, creating a protective bubble around her upper body while water streams down the sides. The red paper crane she held previously is now tucked away or gone, replaced by her grip on the curved umbrella handle. The blurred city lights reflect beautifully on the wet surface of the umbrella as she gazes forward with renewed calmness. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 48 |
+
312,5,"The young woman stands beneath the transparent floral umbrella, the rain creating a rhythmic patter on its surface. She reaches up with her free hand and adjusts a pair of round, gold-rimmed glasses onto the bridge of her nose, blinking behind the lenses as they catch the ambient city light. Her damp hair frames her face, and the light dress clings softly to her form in the humid air. The blurred cityscape behind her glows with the warmth of streetlights, enhancing the serene mood. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 49 |
+
334,0,"A stylish, young woman riding a sleek black motorcycle down a bustling city street. She wears a fitted leather jacket, dark sunglasses, and a helmet with a visor up, revealing her confident expression. Her posture is relaxed yet controlled as she grips the handlebars firmly. The motorcycle's engine roars as she navigates through traffic. The urban backdrop includes tall buildings, street signs, and passing cars, creating a vibrant, dynamic scene. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 50 |
+
334,1,"The stylish young woman on the sleek black motorcycle leans slightly to the right as she smoothly changes lanes. Her fitted leather jacket gleams under the city lights, and her dark sunglasses reflect the passing scenery. With her helmet visor up, a faint smile plays on her lips, showing her enjoyment of the ride. Suddenly, she extends her left hand to adjust the side mirror, briefly checking the reflection of the vibrant urban backdrop behind her before returning her grip to the handlebars. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 51 |
+
334,2,"The stylish young woman on the sleek black motorcycle accelerates gently, causing her hair to flutter beneath the edge of her helmet. Her fitted leather jacket remains snug against the wind, while her dark sunglasses shield her eyes from the glare. As she cruises past towering skyscrapers and vibrant street signs, she reaches down with her right hand to toggle a switch on the dashboard, activating the motorcycle's bright turn signal. The urban environment blurs slightly in the background, emphasizing her focused movement through the traffic. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 52 |
+
334,3,"The stylish young woman on the sleek black motorcycle maintains her steady pace through the busy urban corridor. Her fitted leather jacket and dark sunglasses remain prominent against the backdrop of tall buildings and passing cars. With her helmet visor up, her confident expression is clear as she navigates the road. As she rides, she briefly lifts her left boot to shift gears, pressing down decisively on the pedal near the footrest. The engine note changes pitch slightly, blending with the city noise, while street signs flash by in the background. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 53 |
+
334,4,"The stylish young woman on the sleek black motorcycle rides confidently forward amidst the bustling traffic. Her fitted leather jacket and dark sunglasses stay consistent with her cool demeanor, while the helmet visor remains up. As she passes a row of tall buildings and street signs, she suddenly raises her left hand to wave at a pedestrian standing on the nearby sidewalk. Her posture stays relaxed despite the momentary gesture, and she quickly returns her hand to the grip to maintain control. The urban backdrop continues to provide a vibrant, dynamic atmosphere around her. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 54 |
+
334,5,"The stylish young woman on the sleek black motorcycle rides forward, her fitted leather jacket absorbing the ambient city light. She wears dark sunglasses and keeps her helmet visor up, maintaining a confident, relaxed expression amidst the towering buildings and passing cars. While cruising through the vibrant urban scene, she briefly tilts her head to glance at a large digital billboard flashing colorful advertisements above the street. Her grip on the handlebars remains steady as she takes in the glowing display before refocusing on the road ahead. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
Helios/_DEV/example/toy_data/toy_filter.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"cut": [
|
| 4 |
+
0,
|
| 5 |
+
81
|
| 6 |
+
],
|
| 7 |
+
"crop": [
|
| 8 |
+
0,
|
| 9 |
+
832,
|
| 10 |
+
0,
|
| 11 |
+
480
|
| 12 |
+
],
|
| 13 |
+
"fps": 24.0,
|
| 14 |
+
"num_frames": 81,
|
| 15 |
+
"resolution": {
|
| 16 |
+
"height": 480,
|
| 17 |
+
"width": 832
|
| 18 |
+
},
|
| 19 |
+
"cap": [
|
| 20 |
+
"A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity."
|
| 21 |
+
],
|
| 22 |
+
"path": "videos/2_240_ori81.mp4"
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cut": [
|
| 26 |
+
0,
|
| 27 |
+
129
|
| 28 |
+
],
|
| 29 |
+
"crop": [
|
| 30 |
+
0,
|
| 31 |
+
832,
|
| 32 |
+
0,
|
| 33 |
+
480
|
| 34 |
+
],
|
| 35 |
+
"fps": 24.0,
|
| 36 |
+
"num_frames": 129,
|
| 37 |
+
"resolution": {
|
| 38 |
+
"height": 480,
|
| 39 |
+
"width": 832
|
| 40 |
+
},
|
| 41 |
+
"cap": [
|
| 42 |
+
"An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man."
|
| 43 |
+
],
|
| 44 |
+
"path": "videos/239_120_ori129.mp4"
|
| 45 |
+
}
|
| 46 |
+
]
|
Helios/_DEV/helios/__init__.py
ADDED
|
File without changes
|
Helios/_DEV/helios/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (182 Bytes). View file
|
|
|
Helios/_DEV/helios/dataset/__init__.py
ADDED
|
File without changes
|
Helios/_DEV/helios/dataset/dataloader_dmd.py
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
import random
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from einops import rearrange
|
| 8 |
+
from torch.utils.data import Dataset, Sampler
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class BucketedFeatureDataset(Dataset):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
gan_folders=None,
|
| 15 |
+
ode_folders=None,
|
| 16 |
+
text_folders=None,
|
| 17 |
+
is_use_gt_history=False,
|
| 18 |
+
return_secondary=False,
|
| 19 |
+
force_rebuild=False,
|
| 20 |
+
single_res=True,
|
| 21 |
+
single_length=True,
|
| 22 |
+
single_num_frame=81,
|
| 23 |
+
single_height=384,
|
| 24 |
+
single_width=640,
|
| 25 |
+
seed=42,
|
| 26 |
+
):
|
| 27 |
+
self.is_use_gt_history = is_use_gt_history
|
| 28 |
+
self.return_secondary = return_secondary
|
| 29 |
+
self.force_rebuild = force_rebuild
|
| 30 |
+
self.base_seed = seed
|
| 31 |
+
self._epoch = 0
|
| 32 |
+
|
| 33 |
+
self.single_res = single_res
|
| 34 |
+
self.single_length = single_length
|
| 35 |
+
self.single_num_frame = single_num_frame
|
| 36 |
+
self.single_height = single_height
|
| 37 |
+
self.single_width = single_width
|
| 38 |
+
|
| 39 |
+
self.gan_samples = self._init_samples(gan_folders, "gan")
|
| 40 |
+
self.ode_samples = self._init_samples(ode_folders, "ode")
|
| 41 |
+
self.text_samples = self._init_samples(text_folders, "text")
|
| 42 |
+
|
| 43 |
+
self._align_sample_counts()
|
| 44 |
+
|
| 45 |
+
def _init_samples(self, folders, data_type):
|
| 46 |
+
if folders is None:
|
| 47 |
+
return []
|
| 48 |
+
|
| 49 |
+
folders = [folders] if isinstance(folders, str) else folders
|
| 50 |
+
samples = []
|
| 51 |
+
|
| 52 |
+
for folder in folders:
|
| 53 |
+
cache_file = os.path.join(folder, f"{data_type}_dataset_cache.pkl")
|
| 54 |
+
folder_samples = self._process_folder(folder, cache_file, data_type)
|
| 55 |
+
samples.extend(folder_samples)
|
| 56 |
+
|
| 57 |
+
return samples
|
| 58 |
+
|
| 59 |
+
def _align_sample_counts(self, is_log=True):
|
| 60 |
+
lengths = {"gan": len(self.gan_samples), "ode": len(self.ode_samples), "text": len(self.text_samples)}
|
| 61 |
+
|
| 62 |
+
non_empty_lengths = {k: v for k, v in lengths.items() if v > 0}
|
| 63 |
+
if not non_empty_lengths:
|
| 64 |
+
return
|
| 65 |
+
max_length = max(non_empty_lengths.values())
|
| 66 |
+
|
| 67 |
+
if is_log:
|
| 68 |
+
print(f"\nAligning sample counts to max: {max_length}")
|
| 69 |
+
print(f"Original counts - GAN: {lengths['gan']}, ODE: {lengths['ode']}, TEXT: {lengths['text']}")
|
| 70 |
+
|
| 71 |
+
random.seed(self.base_seed)
|
| 72 |
+
|
| 73 |
+
if self.gan_samples and len(self.gan_samples) < max_length:
|
| 74 |
+
self.gan_samples = self._expand_samples(self.gan_samples, max_length, "GAN")
|
| 75 |
+
|
| 76 |
+
if self.ode_samples and len(self.ode_samples) < max_length:
|
| 77 |
+
self.ode_samples = self._expand_samples(self.ode_samples, max_length, "ODE")
|
| 78 |
+
|
| 79 |
+
if self.text_samples and len(self.text_samples) < max_length:
|
| 80 |
+
self.text_samples = self._expand_samples(self.text_samples, max_length, "TEXT")
|
| 81 |
+
|
| 82 |
+
if is_log:
|
| 83 |
+
print(
|
| 84 |
+
f"Aligned counts - GAN: {len(self.gan_samples)}, ODE: {len(self.ode_samples)}, TEXT: {len(self.text_samples)}\n"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def _expand_samples(self, samples, target_length, data_type):
|
| 88 |
+
original_length = len(samples)
|
| 89 |
+
expanded_samples = samples.copy()
|
| 90 |
+
|
| 91 |
+
while len(expanded_samples) < target_length:
|
| 92 |
+
random_sample = random.choice(samples)
|
| 93 |
+
expanded_samples.append(random_sample)
|
| 94 |
+
|
| 95 |
+
print(f"{data_type}: Expanded from {original_length} to {len(expanded_samples)} samples")
|
| 96 |
+
return expanded_samples
|
| 97 |
+
|
| 98 |
+
def _process_folder(self, folder, cache_file, data_type):
|
| 99 |
+
if self.force_rebuild or not os.path.exists(cache_file):
|
| 100 |
+
# if os.path.exists(cache_file):
|
| 101 |
+
# os.remove(cache_file)
|
| 102 |
+
print(f"{data_type.upper()}: Building metadata cache for folder: {folder}")
|
| 103 |
+
folder_samples = self._build_folder_metadata(folder, data_type)
|
| 104 |
+
|
| 105 |
+
if not self.force_rebuild:
|
| 106 |
+
print(f"{data_type.upper()}: Saving metadata cache for folder: {folder}")
|
| 107 |
+
with open(cache_file, "wb") as f:
|
| 108 |
+
pickle.dump({"samples": folder_samples}, f)
|
| 109 |
+
|
| 110 |
+
print(f"{data_type.upper()}: Cached {len(folder_samples)} samples from {folder}")
|
| 111 |
+
else:
|
| 112 |
+
print(f"{data_type.upper()}: Loading cached metadata from: {folder}")
|
| 113 |
+
with open(cache_file, "rb") as f:
|
| 114 |
+
folder_samples = pickle.load(f)["samples"]
|
| 115 |
+
print(f"{data_type.upper()}: Loaded {len(folder_samples)} samples from cache: {folder}")
|
| 116 |
+
|
| 117 |
+
return folder_samples
|
| 118 |
+
|
| 119 |
+
def _build_folder_metadata(self, folder, data_type):
|
| 120 |
+
feature_files = [f for f in os.listdir(folder) if f.endswith(".pt")]
|
| 121 |
+
samples = []
|
| 122 |
+
|
| 123 |
+
print(f"{data_type.upper()}: Processing {len(feature_files)} files in {folder}...")
|
| 124 |
+
for i, feature_file in enumerate(feature_files):
|
| 125 |
+
if i % 10000 == 0:
|
| 126 |
+
print(f" {data_type.upper()}: Processed {i}/{len(feature_files)} files")
|
| 127 |
+
|
| 128 |
+
feature_path = os.path.join(folder, feature_file)
|
| 129 |
+
|
| 130 |
+
# TODO hard code here now
|
| 131 |
+
if data_type == "gan":
|
| 132 |
+
parts = feature_file.split("_")
|
| 133 |
+
num_frame = int(parts[-3])
|
| 134 |
+
height = int(parts[-2])
|
| 135 |
+
width = int(parts[-1].replace(".pt", ""))
|
| 136 |
+
|
| 137 |
+
if self.is_use_gt_history:
|
| 138 |
+
if (height, width) not in [(self.single_height, self.single_width)]:
|
| 139 |
+
continue
|
| 140 |
+
else:
|
| 141 |
+
if (num_frame, height, width) not in [
|
| 142 |
+
(self.single_num_frame, self.single_height, self.single_width)
|
| 143 |
+
]:
|
| 144 |
+
continue
|
| 145 |
+
|
| 146 |
+
samples.append(
|
| 147 |
+
{
|
| 148 |
+
"uttid": os.path.splitext(os.path.basename(feature_file))[0],
|
| 149 |
+
"dataset_name": folder.rstrip("/"),
|
| 150 |
+
"file_path": feature_path,
|
| 151 |
+
}
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
return samples
|
| 155 |
+
|
| 156 |
+
def prepare_stage1_latent(self, vae_latent, idx, base_vae_latent=None, return_secondary=False):
|
| 157 |
+
self.is_keep_x0 = (True,)
|
| 158 |
+
self.history_sizes = [16, 2, 1]
|
| 159 |
+
self.num_rollout_sections = 9
|
| 160 |
+
|
| 161 |
+
source_latent = base_vae_latent if base_vae_latent is not None else vae_latent
|
| 162 |
+
|
| 163 |
+
x0_latent = None
|
| 164 |
+
if self.is_keep_x0:
|
| 165 |
+
x0_latent = source_latent[0, :, :1, :, :].clone()
|
| 166 |
+
total_sections = source_latent.shape[0]
|
| 167 |
+
latent_window_size = source_latent.shape[2]
|
| 168 |
+
history_window_size = sum(self.history_sizes)
|
| 169 |
+
section_size = history_window_size + latent_window_size
|
| 170 |
+
|
| 171 |
+
temp_source_latent = rearrange(source_latent, "b c t h w -> c (b t) h w")
|
| 172 |
+
zero_padding_source = torch.zeros(
|
| 173 |
+
temp_source_latent.shape[0],
|
| 174 |
+
history_window_size,
|
| 175 |
+
temp_source_latent.shape[2],
|
| 176 |
+
temp_source_latent.shape[3],
|
| 177 |
+
device=temp_source_latent.device,
|
| 178 |
+
dtype=temp_source_latent.dtype,
|
| 179 |
+
)
|
| 180 |
+
continue_source_latent = torch.cat([zero_padding_source, temp_source_latent], dim=1)
|
| 181 |
+
|
| 182 |
+
temp_vae_latent = rearrange(vae_latent, "b c t h w -> c (b t) h w")
|
| 183 |
+
zero_padding_vae = torch.zeros(
|
| 184 |
+
temp_vae_latent.shape[0],
|
| 185 |
+
history_window_size,
|
| 186 |
+
temp_vae_latent.shape[2],
|
| 187 |
+
temp_vae_latent.shape[3],
|
| 188 |
+
device=temp_vae_latent.device,
|
| 189 |
+
dtype=temp_vae_latent.dtype,
|
| 190 |
+
)
|
| 191 |
+
continue_vae_latent = torch.cat([zero_padding_vae, temp_vae_latent], dim=1)
|
| 192 |
+
|
| 193 |
+
sample_seed = self.base_seed + self._epoch * 1000000 + idx
|
| 194 |
+
choice_idx = torch.randint(
|
| 195 |
+
0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed)
|
| 196 |
+
).item()
|
| 197 |
+
if choice_idx == 0 and x0_latent is not None:
|
| 198 |
+
x0_latent = torch.zeros_like(x0_latent)
|
| 199 |
+
|
| 200 |
+
start_indice = choice_idx * latent_window_size
|
| 201 |
+
end_indice = start_indice + section_size
|
| 202 |
+
|
| 203 |
+
history_latent = continue_source_latent[:, start_indice : start_indice + history_window_size, :, :]
|
| 204 |
+
target_latent = continue_vae_latent[:, start_indice + history_window_size : end_indice, :, :]
|
| 205 |
+
|
| 206 |
+
x0_latent_2 = None
|
| 207 |
+
history_latent_2 = None
|
| 208 |
+
target_latent_2 = None
|
| 209 |
+
if return_secondary:
|
| 210 |
+
sample_seed_2 = self.base_seed + self._epoch * 1000000 + idx + 999999
|
| 211 |
+
choice_idx_2 = torch.randint(
|
| 212 |
+
0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed_2)
|
| 213 |
+
).item()
|
| 214 |
+
|
| 215 |
+
x0_latent_2 = None
|
| 216 |
+
if self.is_keep_x0:
|
| 217 |
+
x0_latent_2 = source_latent[0, :, :1, :, :].clone()
|
| 218 |
+
if choice_idx_2 == 0:
|
| 219 |
+
x0_latent_2 = torch.zeros_like(x0_latent_2)
|
| 220 |
+
|
| 221 |
+
start_indice_2 = choice_idx_2 * latent_window_size
|
| 222 |
+
end_indice_2 = start_indice_2 + section_size
|
| 223 |
+
|
| 224 |
+
history_latent_2 = continue_source_latent[:, start_indice_2 : start_indice_2 + history_window_size, :, :]
|
| 225 |
+
target_latent_2 = continue_vae_latent[:, start_indice_2 + history_window_size : end_indice_2, :, :]
|
| 226 |
+
|
| 227 |
+
return (x0_latent, history_latent, target_latent), (x0_latent_2, history_latent_2, target_latent_2)
|
| 228 |
+
|
| 229 |
+
def set_epoch(self, epoch):
|
| 230 |
+
self._epoch = epoch
|
| 231 |
+
random.seed(self.base_seed + epoch)
|
| 232 |
+
self._align_sample_counts(is_log=False)
|
| 233 |
+
|
| 234 |
+
def __len__(self):
|
| 235 |
+
return max(len(self.gan_samples), len(self.ode_samples), len(self.text_samples))
|
| 236 |
+
|
| 237 |
+
def __getitem__(self, idx):
|
| 238 |
+
while True:
|
| 239 |
+
try:
|
| 240 |
+
output_dict = {}
|
| 241 |
+
|
| 242 |
+
if self.gan_samples:
|
| 243 |
+
gan_sample = self.gan_samples[idx]
|
| 244 |
+
gan_feature = torch.load(gan_sample["file_path"], map_location="cpu", weights_only=False)
|
| 245 |
+
if self.is_use_gt_history:
|
| 246 |
+
(
|
| 247 |
+
(x0_latent, history_latent, target_latent),
|
| 248 |
+
(x0_latent_2, history_latent_2, target_latent_2),
|
| 249 |
+
) = self.prepare_stage1_latent(
|
| 250 |
+
gan_feature["vae_latent"],
|
| 251 |
+
idx,
|
| 252 |
+
return_secondary=self.return_secondary,
|
| 253 |
+
)
|
| 254 |
+
output_dict.update(
|
| 255 |
+
{
|
| 256 |
+
"gan_uttid": gan_sample["uttid"],
|
| 257 |
+
"gan_dataset_name": gan_sample["dataset_name"],
|
| 258 |
+
"gan_vae_latents": target_latent,
|
| 259 |
+
"gan_x0_latents": x0_latent,
|
| 260 |
+
"gan_history_latents": history_latent,
|
| 261 |
+
"gan_vae_latents_2": target_latent_2,
|
| 262 |
+
"gan_x0_latents_2": x0_latent_2,
|
| 263 |
+
"gan_history_latents_2": history_latent_2,
|
| 264 |
+
"gan_prompt_raws": gan_feature["prompt_raw"],
|
| 265 |
+
"gan_prompt_embeds": gan_feature["prompt_embed"],
|
| 266 |
+
}
|
| 267 |
+
)
|
| 268 |
+
else:
|
| 269 |
+
output_dict.update(
|
| 270 |
+
{
|
| 271 |
+
"gan_uttid": gan_sample["uttid"],
|
| 272 |
+
"gan_dataset_name": gan_sample["dataset_name"],
|
| 273 |
+
"gan_vae_latents": gan_feature["vae_latent"],
|
| 274 |
+
"gan_prompt_raws": gan_feature["prompt_raw"],
|
| 275 |
+
"gan_prompt_embeds": gan_feature["prompt_embed"],
|
| 276 |
+
}
|
| 277 |
+
)
|
| 278 |
+
gan_sample = None
|
| 279 |
+
gan_feature = None
|
| 280 |
+
del gan_sample
|
| 281 |
+
del gan_feature
|
| 282 |
+
|
| 283 |
+
if self.ode_samples:
|
| 284 |
+
ode_sample = self.ode_samples[idx]
|
| 285 |
+
ode_feature = torch.load(ode_sample["file_path"], map_location="cpu", weights_only=False)
|
| 286 |
+
output_dict.update(
|
| 287 |
+
{
|
| 288 |
+
"ode_uttid": ode_sample["uttid"],
|
| 289 |
+
"ode_dataset_name": ode_sample["dataset_name"],
|
| 290 |
+
"ode_latent_window_size": ode_feature["latent_window_size"],
|
| 291 |
+
"ode_latents": ode_feature["ode_latents"],
|
| 292 |
+
"ode_prompt_raws": ode_feature["prompt_raw"],
|
| 293 |
+
"ode_prompt_embeds": ode_feature["prompt_embed"][0],
|
| 294 |
+
}
|
| 295 |
+
)
|
| 296 |
+
ode_sample = None
|
| 297 |
+
ode_feature = None
|
| 298 |
+
del ode_sample
|
| 299 |
+
del ode_feature
|
| 300 |
+
|
| 301 |
+
if self.text_samples:
|
| 302 |
+
text_sample = self.text_samples[idx]
|
| 303 |
+
text_feature = torch.load(text_sample["file_path"], map_location="cpu", weights_only=False)
|
| 304 |
+
output_dict.update(
|
| 305 |
+
{
|
| 306 |
+
"text_uttid": text_sample["uttid"],
|
| 307 |
+
"text_dataset_name": text_sample["dataset_name"],
|
| 308 |
+
"text_prompt_raws": text_feature["prompt_raw"],
|
| 309 |
+
"text_prompt_embeds": text_feature["prompt_embed"],
|
| 310 |
+
}
|
| 311 |
+
)
|
| 312 |
+
text_sample = None
|
| 313 |
+
text_feature = None
|
| 314 |
+
del text_sample
|
| 315 |
+
del text_feature
|
| 316 |
+
|
| 317 |
+
return output_dict
|
| 318 |
+
|
| 319 |
+
except Exception as e:
|
| 320 |
+
idx = random.randint(0, len(self) - 1)
|
| 321 |
+
print(f"Error loading sample at idx {idx}, retrying... Error: {e}")
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class BucketedSampler(Sampler):
|
| 325 |
+
def __init__(
|
| 326 |
+
self,
|
| 327 |
+
dataset,
|
| 328 |
+
batch_size,
|
| 329 |
+
dataset_sampling_ratios={},
|
| 330 |
+
drop_last=False,
|
| 331 |
+
shuffle=True,
|
| 332 |
+
seed=42,
|
| 333 |
+
num_sp_groups=1,
|
| 334 |
+
sp_world_size=1,
|
| 335 |
+
global_rank=0,
|
| 336 |
+
):
|
| 337 |
+
self.dataset = dataset
|
| 338 |
+
self.batch_size = batch_size
|
| 339 |
+
self.drop_last = drop_last
|
| 340 |
+
self.shuffle = shuffle
|
| 341 |
+
self.seed = seed
|
| 342 |
+
self.generator = torch.Generator()
|
| 343 |
+
self._epoch = 0
|
| 344 |
+
|
| 345 |
+
# Distributed parameters
|
| 346 |
+
self.num_sp_groups = num_sp_groups
|
| 347 |
+
self.sp_world_size = sp_world_size
|
| 348 |
+
self.global_rank = global_rank
|
| 349 |
+
self.ith_sp_group = self.global_rank // self.sp_world_size
|
| 350 |
+
|
| 351 |
+
def set_epoch(self, epoch):
|
| 352 |
+
self._epoch = epoch
|
| 353 |
+
|
| 354 |
+
def _shard_indices_for_sp_group(self, indices):
|
| 355 |
+
"""
|
| 356 |
+
Shard indices across SP groups.
|
| 357 |
+
Each SP group gets a disjoint subset of the data.
|
| 358 |
+
"""
|
| 359 |
+
if self.num_sp_groups == 1:
|
| 360 |
+
return indices
|
| 361 |
+
|
| 362 |
+
# Convert to tensor if it's a list
|
| 363 |
+
if isinstance(indices, list):
|
| 364 |
+
indices_tensor = torch.tensor(indices, dtype=torch.long)
|
| 365 |
+
else:
|
| 366 |
+
indices_tensor = indices
|
| 367 |
+
|
| 368 |
+
# Pad indices if necessary to make it divisible by num_sp_groups
|
| 369 |
+
total_size = len(indices_tensor)
|
| 370 |
+
if total_size % self.num_sp_groups != 0:
|
| 371 |
+
if not self.drop_last:
|
| 372 |
+
padding_size = self.num_sp_groups - (total_size % self.num_sp_groups)
|
| 373 |
+
indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]])
|
| 374 |
+
else:
|
| 375 |
+
# If drop_last, truncate to be divisible
|
| 376 |
+
if self.drop_last:
|
| 377 |
+
truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups
|
| 378 |
+
indices_tensor = indices_tensor[:truncate_size]
|
| 379 |
+
|
| 380 |
+
# Shard: each SP group gets every num_sp_groups-th element
|
| 381 |
+
sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups]
|
| 382 |
+
|
| 383 |
+
return sp_group_indices.tolist()
|
| 384 |
+
|
| 385 |
+
def __iter__(self):
|
| 386 |
+
# Use epoch-level seed for reproducibility
|
| 387 |
+
epoch_seed = self.seed + self._epoch
|
| 388 |
+
self.generator.manual_seed(epoch_seed)
|
| 389 |
+
|
| 390 |
+
# Get all indices
|
| 391 |
+
all_indices = list(range(len(self.dataset)))
|
| 392 |
+
|
| 393 |
+
# Global shuffle before sharding (important for distributed consistency)
|
| 394 |
+
if self.shuffle:
|
| 395 |
+
perm = torch.randperm(len(all_indices), generator=self.generator).tolist()
|
| 396 |
+
all_indices = [all_indices[i] for i in perm]
|
| 397 |
+
|
| 398 |
+
# Shard indices for this SP group
|
| 399 |
+
sp_group_indices = self._shard_indices_for_sp_group(all_indices)
|
| 400 |
+
|
| 401 |
+
# Create batches
|
| 402 |
+
for i in range(0, len(sp_group_indices), self.batch_size):
|
| 403 |
+
batch = sp_group_indices[i : i + self.batch_size]
|
| 404 |
+
if len(batch) == self.batch_size or not self.drop_last:
|
| 405 |
+
yield batch
|
| 406 |
+
|
| 407 |
+
def __len__(self):
|
| 408 |
+
# Total samples in dataset
|
| 409 |
+
total_samples = len(self.dataset)
|
| 410 |
+
|
| 411 |
+
# Account for SP group sharding
|
| 412 |
+
sp_group_samples = total_samples // self.num_sp_groups
|
| 413 |
+
if not self.drop_last and total_samples % self.num_sp_groups != 0:
|
| 414 |
+
sp_group_samples += 1
|
| 415 |
+
|
| 416 |
+
# Calculate number of batches
|
| 417 |
+
total_batches = sp_group_samples // self.batch_size
|
| 418 |
+
if not self.drop_last and sp_group_samples % self.batch_size != 0:
|
| 419 |
+
total_batches += 1
|
| 420 |
+
|
| 421 |
+
return total_batches
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def collate_fn(batch):
|
| 425 |
+
return {
|
| 426 |
+
key: torch.stack([d[key] for d in batch])
|
| 427 |
+
if isinstance(batch[0][key], torch.Tensor)
|
| 428 |
+
else [d[key] for d in batch]
|
| 429 |
+
for key in batch[0]
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
if __name__ == "__main__":
|
| 434 |
+
from accelerate import Accelerator
|
| 435 |
+
from torchdata.stateful_dataloader import StatefulDataLoader
|
| 436 |
+
|
| 437 |
+
dataloader_num_workers = 8
|
| 438 |
+
batch_size = 2
|
| 439 |
+
num_train_epochs = 2
|
| 440 |
+
seed = 0
|
| 441 |
+
|
| 442 |
+
gan_folder = [
|
| 443 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_long_960",
|
| 444 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_short_960",
|
| 445 |
+
]
|
| 446 |
+
ode_folder = [
|
| 447 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/ode_pairs/vidprom_filtered_extended",
|
| 448 |
+
]
|
| 449 |
+
text_folder = [
|
| 450 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/text-embedding/mixkit_filter",
|
| 451 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/text-embedding/vidprom_filtered_extended",
|
| 452 |
+
]
|
| 453 |
+
|
| 454 |
+
accelerator = Accelerator()
|
| 455 |
+
print(accelerator.process_index, accelerator.num_processes)
|
| 456 |
+
|
| 457 |
+
dataset = BucketedFeatureDataset(
|
| 458 |
+
gan_folders=gan_folder,
|
| 459 |
+
ode_folders=ode_folder,
|
| 460 |
+
text_folders=text_folder,
|
| 461 |
+
is_use_gt_history=True,
|
| 462 |
+
force_rebuild=True,
|
| 463 |
+
seed=seed,
|
| 464 |
+
)
|
| 465 |
+
sampler = BucketedSampler(
|
| 466 |
+
dataset,
|
| 467 |
+
batch_size=batch_size,
|
| 468 |
+
drop_last=True,
|
| 469 |
+
shuffle=True,
|
| 470 |
+
seed=seed,
|
| 471 |
+
num_sp_groups=accelerator.num_processes // 1,
|
| 472 |
+
sp_world_size=1,
|
| 473 |
+
global_rank=accelerator.process_index,
|
| 474 |
+
)
|
| 475 |
+
dataloader = StatefulDataLoader(
|
| 476 |
+
dataset,
|
| 477 |
+
batch_sampler=sampler,
|
| 478 |
+
collate_fn=collate_fn,
|
| 479 |
+
num_workers=dataloader_num_workers,
|
| 480 |
+
prefetch_factor=2 if dataloader_num_workers > 0 else None,
|
| 481 |
+
)
|
| 482 |
+
print(len(dataset), len(dataloader))
|
| 483 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 484 |
+
|
| 485 |
+
step = 0
|
| 486 |
+
global_step = 0
|
| 487 |
+
first_epoch = 0
|
| 488 |
+
print("Testing dataloader...")
|
| 489 |
+
dataset_counts = defaultdict(int)
|
| 490 |
+
for epoch in range(first_epoch, num_train_epochs):
|
| 491 |
+
sampler.set_epoch(epoch)
|
| 492 |
+
dataset.set_epoch(epoch)
|
| 493 |
+
for i, batch in enumerate(dataloader):
|
| 494 |
+
# Get metadata
|
| 495 |
+
gan_uttid = batch["gan_uttid"]
|
| 496 |
+
ode_uttid = batch["ode_uttid"]
|
| 497 |
+
text_uttid = batch["text_uttid"]
|
| 498 |
+
|
| 499 |
+
# Get feature
|
| 500 |
+
# For GAN
|
| 501 |
+
gan_vae_latents = batch["gan_vae_latents"]
|
| 502 |
+
gan_prompt_raws = batch["gan_prompt_raws"]
|
| 503 |
+
gan_prompt_embeds = batch["gan_prompt_embeds"]
|
| 504 |
+
print(gan_vae_latents.shape, gan_prompt_embeds.shape, gan_prompt_raws)
|
| 505 |
+
|
| 506 |
+
# For ODE
|
| 507 |
+
ode_prompt_raws = batch["ode_prompt_raws"]
|
| 508 |
+
ode_prompt_embeds = batch["ode_prompt_embeds"]
|
| 509 |
+
print(ode_prompt_embeds.shape, ode_prompt_raws)
|
| 510 |
+
|
| 511 |
+
# For Text
|
| 512 |
+
text_prompt_raws = batch["text_prompt_raws"]
|
| 513 |
+
text_prompt_embeds = batch["text_prompt_embeds"]
|
| 514 |
+
print(text_prompt_embeds.shape, text_prompt_raws)
|
| 515 |
+
|
| 516 |
+
if accelerator.process_index == 0:
|
| 517 |
+
# print info
|
| 518 |
+
print(f" Step {step}:")
|
| 519 |
+
print(f" Batch {i}:")
|
| 520 |
+
print(f" Batch size: {len(gan_uttid)}")
|
| 521 |
+
print(f" Uttids: {gan_uttid}, {ode_uttid}, {text_uttid}")
|
| 522 |
+
print(
|
| 523 |
+
f" Data Name: {batch['gan_dataset_name']}, {batch['ode_dataset_name']}, {batch['text_dataset_name']}"
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
for dataset_name in batch["gan_dataset_name"]:
|
| 527 |
+
dataset_counts[dataset_name] += 1
|
| 528 |
+
|
| 529 |
+
step += 1
|
| 530 |
+
|
| 531 |
+
print("实际采样统计:", dict(dataset_counts))
|
Helios/_DEV/helios/dataset/dataloader_history_latents_dist.py
ADDED
|
@@ -0,0 +1,685 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
import random
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from einops import rearrange
|
| 8 |
+
from torch.utils.data import Dataset, Sampler
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class BucketedFeatureDataset(Dataset):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
feature_folders,
|
| 15 |
+
history_sizes=[16, 2, 1],
|
| 16 |
+
is_keep_x0=True,
|
| 17 |
+
force_rebuild=False,
|
| 18 |
+
return_all_vae_latent=False,
|
| 19 |
+
return_prompt_raw=False,
|
| 20 |
+
num_rollout_sections=3,
|
| 21 |
+
single_res=False,
|
| 22 |
+
single_height=384,
|
| 23 |
+
single_width=640,
|
| 24 |
+
seed=42,
|
| 25 |
+
):
|
| 26 |
+
self.history_sizes = history_sizes
|
| 27 |
+
self.is_keep_x0 = is_keep_x0
|
| 28 |
+
self.force_rebuild = force_rebuild
|
| 29 |
+
self.return_all_vae_latent = return_all_vae_latent
|
| 30 |
+
self.return_prompt_raw = return_prompt_raw
|
| 31 |
+
self.num_rollout_sections = num_rollout_sections
|
| 32 |
+
self.single_res = single_res
|
| 33 |
+
self.single_height = single_height
|
| 34 |
+
self.single_width = single_width
|
| 35 |
+
assert self.is_keep_x0, "is_keep_x0 need to be True now!"
|
| 36 |
+
|
| 37 |
+
self.base_seed = seed
|
| 38 |
+
self._epoch = 0
|
| 39 |
+
|
| 40 |
+
if isinstance(feature_folders, str):
|
| 41 |
+
self.feature_folders = [feature_folders]
|
| 42 |
+
else:
|
| 43 |
+
self.feature_folders = feature_folders
|
| 44 |
+
|
| 45 |
+
self.samples = []
|
| 46 |
+
self.buckets = defaultdict(list)
|
| 47 |
+
|
| 48 |
+
for folder in self.feature_folders:
|
| 49 |
+
cache_file = os.path.join(folder, "dataset_cache.pkl")
|
| 50 |
+
self._process_folder(folder, cache_file)
|
| 51 |
+
|
| 52 |
+
def _process_folder(self, folder, cache_file):
|
| 53 |
+
if self.force_rebuild or not os.path.exists(cache_file):
|
| 54 |
+
print(f"Building metadata cache for folder: {folder}")
|
| 55 |
+
folder_samples, folder_buckets = self._build_folder_metadata(folder)
|
| 56 |
+
|
| 57 |
+
print(f"Saving metadata cache for folder: {folder}")
|
| 58 |
+
cached_data = {"samples": folder_samples, "buckets": folder_buckets}
|
| 59 |
+
if not self.force_rebuild:
|
| 60 |
+
with open(cache_file, "wb") as f:
|
| 61 |
+
pickle.dump(cached_data, f)
|
| 62 |
+
print(f"Cached {len(folder_samples)} samples from {folder}\n")
|
| 63 |
+
else:
|
| 64 |
+
print(f"Loading cached metadata from: {folder}")
|
| 65 |
+
with open(cache_file, "rb") as f:
|
| 66 |
+
cached_data = pickle.load(f)
|
| 67 |
+
folder_samples = cached_data["samples"]
|
| 68 |
+
folder_buckets = cached_data["buckets"]
|
| 69 |
+
print(f"Loaded {len(folder_samples)} samples from cache: {folder}\n")
|
| 70 |
+
|
| 71 |
+
sample_idx_offset = len(self.samples)
|
| 72 |
+
self.samples.extend(folder_samples)
|
| 73 |
+
|
| 74 |
+
for bucket_key, indices in folder_buckets.items():
|
| 75 |
+
adjusted_indices = [idx + sample_idx_offset for idx in indices]
|
| 76 |
+
self.buckets[bucket_key].extend(adjusted_indices)
|
| 77 |
+
|
| 78 |
+
def _build_folder_metadata(self, folder):
|
| 79 |
+
feature_files = [f for f in os.listdir(folder) if f.endswith(".pt")]
|
| 80 |
+
samples = []
|
| 81 |
+
buckets = defaultdict(list)
|
| 82 |
+
sample_idx = 0
|
| 83 |
+
|
| 84 |
+
print(f"Processing {len(feature_files)} files in {folder}...")
|
| 85 |
+
|
| 86 |
+
for i, feature_file in enumerate(feature_files):
|
| 87 |
+
if i % 10000 == 0:
|
| 88 |
+
print(f" Processed {i}/{len(feature_files)} files")
|
| 89 |
+
|
| 90 |
+
feature_path = os.path.join(folder, feature_file)
|
| 91 |
+
|
| 92 |
+
# Parse filename
|
| 93 |
+
parts = feature_file.split("_")
|
| 94 |
+
uttid = "_".join(parts[:-3])
|
| 95 |
+
num_frame = int(parts[-3])
|
| 96 |
+
height = int(parts[-2])
|
| 97 |
+
width = int(parts[-1].replace(".pt", ""))
|
| 98 |
+
|
| 99 |
+
# keep length >= 121
|
| 100 |
+
if num_frame < 121:
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
# keep resolution
|
| 104 |
+
allowed_resolutions = [
|
| 105 |
+
(self.single_height, self.single_width),
|
| 106 |
+
(self.single_height // 2, self.single_width // 2),
|
| 107 |
+
(self.single_height // 4, self.single_width // 4),
|
| 108 |
+
]
|
| 109 |
+
if self.single_res and (height, width) not in allowed_resolutions:
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
bucket_key = (num_frame, height, width)
|
| 113 |
+
|
| 114 |
+
sample_info = {
|
| 115 |
+
"uttid": uttid,
|
| 116 |
+
"dataset_name": folder.rstrip("/"),
|
| 117 |
+
"file_path": feature_path,
|
| 118 |
+
"bucket_key": bucket_key,
|
| 119 |
+
"num_frame": num_frame,
|
| 120 |
+
"height": height,
|
| 121 |
+
"width": width,
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
samples.append(sample_info)
|
| 125 |
+
buckets[bucket_key].append(sample_idx)
|
| 126 |
+
sample_idx += 1
|
| 127 |
+
|
| 128 |
+
return samples, buckets
|
| 129 |
+
|
| 130 |
+
def set_epoch(self, epoch):
|
| 131 |
+
self._epoch = epoch
|
| 132 |
+
|
| 133 |
+
def prepare_stage1_latent(self, vae_latent, idx, base_vae_latent=None):
|
| 134 |
+
source_latent = base_vae_latent if base_vae_latent is not None else vae_latent
|
| 135 |
+
|
| 136 |
+
x0_latent = None
|
| 137 |
+
if self.is_keep_x0:
|
| 138 |
+
x0_latent = source_latent[0, :, :1, :, :].clone()
|
| 139 |
+
total_sections = source_latent.shape[0]
|
| 140 |
+
latent_window_size = source_latent.shape[2]
|
| 141 |
+
history_window_size = sum(self.history_sizes)
|
| 142 |
+
section_size = history_window_size + latent_window_size
|
| 143 |
+
|
| 144 |
+
temp_source_latent = rearrange(source_latent, "b c t h w -> c (b t) h w")
|
| 145 |
+
zero_padding_source = torch.zeros(
|
| 146 |
+
temp_source_latent.shape[0],
|
| 147 |
+
history_window_size,
|
| 148 |
+
temp_source_latent.shape[2],
|
| 149 |
+
temp_source_latent.shape[3],
|
| 150 |
+
device=temp_source_latent.device,
|
| 151 |
+
dtype=temp_source_latent.dtype,
|
| 152 |
+
)
|
| 153 |
+
continue_source_latent = torch.cat([zero_padding_source, temp_source_latent], dim=1)
|
| 154 |
+
|
| 155 |
+
temp_vae_latent = rearrange(vae_latent, "b c t h w -> c (b t) h w")
|
| 156 |
+
zero_padding_vae = torch.zeros(
|
| 157 |
+
temp_vae_latent.shape[0],
|
| 158 |
+
history_window_size,
|
| 159 |
+
temp_vae_latent.shape[2],
|
| 160 |
+
temp_vae_latent.shape[3],
|
| 161 |
+
device=temp_vae_latent.device,
|
| 162 |
+
dtype=temp_vae_latent.dtype,
|
| 163 |
+
)
|
| 164 |
+
continue_vae_latent = torch.cat([zero_padding_vae, temp_vae_latent], dim=1)
|
| 165 |
+
|
| 166 |
+
sample_seed = self.base_seed + self._epoch * 1000000 + idx
|
| 167 |
+
choice_idx = torch.randint(
|
| 168 |
+
0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed)
|
| 169 |
+
).item()
|
| 170 |
+
if choice_idx == 0 and x0_latent is not None:
|
| 171 |
+
x0_latent = torch.zeros_like(x0_latent)
|
| 172 |
+
|
| 173 |
+
clean_all_vae_latent = None
|
| 174 |
+
if self.return_all_vae_latent:
|
| 175 |
+
max_start_idx = total_sections - self.num_rollout_sections
|
| 176 |
+
if max_start_idx < 0:
|
| 177 |
+
raise ValueError(
|
| 178 |
+
f"Not enough sections: total_sections={total_sections}, num_rollout_sections={self.num_rollout_sections}"
|
| 179 |
+
)
|
| 180 |
+
start_section_idx = random.randint(0, max_start_idx)
|
| 181 |
+
start_indice = start_section_idx * latent_window_size
|
| 182 |
+
end_indice = start_indice + history_window_size + self.num_rollout_sections * latent_window_size
|
| 183 |
+
clean_all_vae_latent = continue_source_latent[:, start_indice:end_indice, :, :]
|
| 184 |
+
|
| 185 |
+
start_indice = choice_idx * latent_window_size
|
| 186 |
+
end_indice = start_indice + section_size
|
| 187 |
+
|
| 188 |
+
history_latent = continue_source_latent[:, start_indice : start_indice + history_window_size, :, :]
|
| 189 |
+
target_latent = continue_vae_latent[:, start_indice + history_window_size : end_indice, :, :]
|
| 190 |
+
|
| 191 |
+
return x0_latent, history_latent, target_latent, clean_all_vae_latent
|
| 192 |
+
|
| 193 |
+
def __len__(self):
|
| 194 |
+
return len(self.samples)
|
| 195 |
+
|
| 196 |
+
def __getitem__(self, idx):
|
| 197 |
+
anchor_f = self.samples[idx]["num_frame"]
|
| 198 |
+
anchor_h = self.samples[idx]["height"]
|
| 199 |
+
anchor_w = self.samples[idx]["width"]
|
| 200 |
+
while True:
|
| 201 |
+
sample_info = self.samples[idx]
|
| 202 |
+
|
| 203 |
+
if (
|
| 204 |
+
anchor_f != sample_info["num_frame"]
|
| 205 |
+
or anchor_h != sample_info["height"]
|
| 206 |
+
or anchor_w != sample_info["width"]
|
| 207 |
+
):
|
| 208 |
+
idx = random.randint(0, len(self.samples) - 1)
|
| 209 |
+
print("Try to find a same dim sample, retrying...")
|
| 210 |
+
continue
|
| 211 |
+
|
| 212 |
+
try:
|
| 213 |
+
base_vae_latent = None
|
| 214 |
+
if (anchor_h, anchor_w) in [
|
| 215 |
+
(self.single_height // 2, self.single_width // 2),
|
| 216 |
+
(self.single_height // 4, self.single_width // 4),
|
| 217 |
+
]:
|
| 218 |
+
base_file_path = (
|
| 219 |
+
sample_info["file_path"]
|
| 220 |
+
.replace("/mid", "")
|
| 221 |
+
.replace("/low", "")
|
| 222 |
+
.replace(
|
| 223 |
+
f"{self.single_height // 2}_{self.single_width // 2}",
|
| 224 |
+
f"{self.single_height}_{self.single_width}",
|
| 225 |
+
)
|
| 226 |
+
.replace(
|
| 227 |
+
f"{self.single_height // 4}_{self.single_width // 4}",
|
| 228 |
+
f"{self.single_height}_{self.single_width}",
|
| 229 |
+
)
|
| 230 |
+
)
|
| 231 |
+
base_vae_latent = torch.load(base_file_path, map_location="cpu", weights_only=False)["vae_latent"]
|
| 232 |
+
|
| 233 |
+
feature_data = torch.load(sample_info["file_path"], map_location="cpu", weights_only=False)
|
| 234 |
+
x0_latent, history_latent, target_latent, clean_all_vae_latent = self.prepare_stage1_latent(
|
| 235 |
+
feature_data["vae_latent"], idx, base_vae_latent
|
| 236 |
+
)
|
| 237 |
+
if self.return_prompt_raw:
|
| 238 |
+
prompt_raws = feature_data["prompt_raw"]
|
| 239 |
+
break
|
| 240 |
+
except Exception:
|
| 241 |
+
idx = random.randint(0, len(self.samples) - 1)
|
| 242 |
+
print(f"Error loading {sample_info['file_path']}, retrying...")
|
| 243 |
+
file_name = os.path.basename(sample_info["file_path"])
|
| 244 |
+
txt_name = f"{file_name}.txt"
|
| 245 |
+
with open(txt_name, "w") as f:
|
| 246 |
+
f.write(sample_info["file_path"] + "\n")
|
| 247 |
+
|
| 248 |
+
output_dict = {
|
| 249 |
+
"uttid": sample_info["uttid"],
|
| 250 |
+
"bucket_key": sample_info["bucket_key"],
|
| 251 |
+
"dataset_name": sample_info["dataset_name"],
|
| 252 |
+
"num_frame": sample_info["num_frame"],
|
| 253 |
+
"height": sample_info["height"],
|
| 254 |
+
"width": sample_info["width"],
|
| 255 |
+
"x0_latents": x0_latent,
|
| 256 |
+
"history_latents": history_latent,
|
| 257 |
+
"target_latents": target_latent,
|
| 258 |
+
"clean_all_latents": clean_all_vae_latent,
|
| 259 |
+
"prompt_embeds": feature_data["prompt_embed"],
|
| 260 |
+
"prompt_attention_masks": feature_data.get("prompt_attention_mask", None),
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
if self.return_prompt_raw:
|
| 264 |
+
output_dict["prompt_raws"] = prompt_raws
|
| 265 |
+
|
| 266 |
+
return output_dict
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class BucketedSampler(Sampler):
|
| 270 |
+
def __init__(
|
| 271 |
+
self,
|
| 272 |
+
dataset,
|
| 273 |
+
batch_size,
|
| 274 |
+
drop_last=False,
|
| 275 |
+
shuffle=True,
|
| 276 |
+
seed=42,
|
| 277 |
+
dataset_sampling_ratios=None,
|
| 278 |
+
num_sp_groups=1,
|
| 279 |
+
sp_world_size=1,
|
| 280 |
+
global_rank=0,
|
| 281 |
+
):
|
| 282 |
+
self.dataset = dataset
|
| 283 |
+
self.batch_size = batch_size
|
| 284 |
+
self.drop_last = drop_last
|
| 285 |
+
self.shuffle = shuffle
|
| 286 |
+
self.seed = seed
|
| 287 |
+
self.generator = torch.Generator()
|
| 288 |
+
self.buckets = dataset.buckets
|
| 289 |
+
self._epoch = 0
|
| 290 |
+
|
| 291 |
+
# Distributed parameters
|
| 292 |
+
self.num_sp_groups = num_sp_groups
|
| 293 |
+
self.sp_world_size = sp_world_size
|
| 294 |
+
self.global_rank = global_rank
|
| 295 |
+
self.ith_sp_group = self.global_rank // self.sp_world_size
|
| 296 |
+
|
| 297 |
+
self.dataset_sampling_ratios = (
|
| 298 |
+
{key.rstrip("/"): value for key, value in dataset_sampling_ratios.items()}
|
| 299 |
+
if dataset_sampling_ratios is not None
|
| 300 |
+
else {}
|
| 301 |
+
)
|
| 302 |
+
self._prepare_dataset_buckets()
|
| 303 |
+
|
| 304 |
+
def _prepare_dataset_buckets(self):
|
| 305 |
+
self.dataset_buckets = {}
|
| 306 |
+
|
| 307 |
+
for bucket_key, sample_indices in self.buckets.items():
|
| 308 |
+
dataset_groups = {}
|
| 309 |
+
for idx in sample_indices:
|
| 310 |
+
dataset_name = self.dataset.samples[idx]["dataset_name"]
|
| 311 |
+
if dataset_name not in dataset_groups:
|
| 312 |
+
dataset_groups[dataset_name] = []
|
| 313 |
+
dataset_groups[dataset_name].append(idx)
|
| 314 |
+
self.dataset_buckets[bucket_key] = dataset_groups
|
| 315 |
+
|
| 316 |
+
def set_epoch(self, epoch):
|
| 317 |
+
self._epoch = epoch
|
| 318 |
+
|
| 319 |
+
def _shard_indices_for_sp_group(self, indices):
|
| 320 |
+
"""
|
| 321 |
+
Shard indices across SP groups, similar to DP_SP_BatchSampler.
|
| 322 |
+
Each SP group gets a disjoint subset of the data.
|
| 323 |
+
"""
|
| 324 |
+
if self.num_sp_groups == 1:
|
| 325 |
+
return indices
|
| 326 |
+
|
| 327 |
+
# Convert to tensor if it's a list
|
| 328 |
+
if isinstance(indices, list):
|
| 329 |
+
indices_tensor = torch.tensor(indices, dtype=torch.long)
|
| 330 |
+
else:
|
| 331 |
+
indices_tensor = indices
|
| 332 |
+
|
| 333 |
+
# Pad indices if necessary to make it divisible by num_sp_groups
|
| 334 |
+
total_size = len(indices_tensor)
|
| 335 |
+
if total_size % self.num_sp_groups != 0:
|
| 336 |
+
if not self.drop_last:
|
| 337 |
+
padding_size = self.num_sp_groups - (total_size % self.num_sp_groups)
|
| 338 |
+
indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]])
|
| 339 |
+
else:
|
| 340 |
+
# If drop_last, truncate to be divisible
|
| 341 |
+
if self.drop_last:
|
| 342 |
+
truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups
|
| 343 |
+
indices_tensor = indices_tensor[:truncate_size]
|
| 344 |
+
|
| 345 |
+
# Shard: each SP group gets every num_sp_groups-th element
|
| 346 |
+
sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups]
|
| 347 |
+
|
| 348 |
+
return sp_group_indices.tolist()
|
| 349 |
+
|
| 350 |
+
def _apply_global_ratio_sampling(self):
|
| 351 |
+
if not self.dataset_sampling_ratios:
|
| 352 |
+
return
|
| 353 |
+
|
| 354 |
+
dataset_sample_map = {}
|
| 355 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 356 |
+
for dataset_name, indices in dataset_groups.items():
|
| 357 |
+
if dataset_name not in dataset_sample_map:
|
| 358 |
+
dataset_sample_map[dataset_name] = {"indices": [], "buckets": []}
|
| 359 |
+
dataset_sample_map[dataset_name]["indices"].extend(indices)
|
| 360 |
+
dataset_sample_map[dataset_name]["buckets"].extend([bucket_key] * len(indices))
|
| 361 |
+
|
| 362 |
+
total_samples = sum(len(info["indices"]) for info in dataset_sample_map.values())
|
| 363 |
+
total_ratio = sum(self.dataset_sampling_ratios.values())
|
| 364 |
+
|
| 365 |
+
sampled_dataset_map = {}
|
| 366 |
+
for dataset_name, info in dataset_sample_map.items():
|
| 367 |
+
if dataset_name in self.dataset_sampling_ratios:
|
| 368 |
+
ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio
|
| 369 |
+
target_samples = max(1, int(total_samples * ratio))
|
| 370 |
+
|
| 371 |
+
indices = info["indices"]
|
| 372 |
+
buckets = info["buckets"]
|
| 373 |
+
|
| 374 |
+
if len(indices) >= target_samples:
|
| 375 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:target_samples].tolist()
|
| 376 |
+
sampled_indices = [indices[i] for i in selected]
|
| 377 |
+
sampled_buckets = [buckets[i] for i in selected]
|
| 378 |
+
else:
|
| 379 |
+
sampled_indices = []
|
| 380 |
+
sampled_buckets = []
|
| 381 |
+
remaining = target_samples
|
| 382 |
+
|
| 383 |
+
while remaining > 0:
|
| 384 |
+
repeat_count = min(remaining, len(indices))
|
| 385 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:repeat_count].tolist()
|
| 386 |
+
sampled_indices.extend([indices[i] for i in selected])
|
| 387 |
+
sampled_buckets.extend([buckets[i] for i in selected])
|
| 388 |
+
remaining -= repeat_count
|
| 389 |
+
|
| 390 |
+
sampled_dataset_map[dataset_name] = {"indices": sampled_indices, "buckets": sampled_buckets}
|
| 391 |
+
else:
|
| 392 |
+
sampled_dataset_map[dataset_name] = info
|
| 393 |
+
|
| 394 |
+
new_dataset_buckets = {}
|
| 395 |
+
for bucket_key in self.dataset_buckets.keys():
|
| 396 |
+
new_dataset_buckets[bucket_key] = {}
|
| 397 |
+
|
| 398 |
+
for dataset_name, info in sampled_dataset_map.items():
|
| 399 |
+
indices = info["indices"]
|
| 400 |
+
buckets = info["buckets"]
|
| 401 |
+
|
| 402 |
+
for idx, bucket_key in zip(indices, buckets):
|
| 403 |
+
if dataset_name not in new_dataset_buckets[bucket_key]:
|
| 404 |
+
new_dataset_buckets[bucket_key][dataset_name] = []
|
| 405 |
+
new_dataset_buckets[bucket_key][dataset_name].append(idx)
|
| 406 |
+
|
| 407 |
+
self.dataset_buckets = new_dataset_buckets
|
| 408 |
+
|
| 409 |
+
def __iter__(self):
|
| 410 |
+
# Use epoch-level seed for reproducibility
|
| 411 |
+
epoch_seed = self.seed + self._epoch
|
| 412 |
+
self.generator.manual_seed(epoch_seed)
|
| 413 |
+
|
| 414 |
+
if self.dataset_sampling_ratios:
|
| 415 |
+
self._apply_global_ratio_sampling()
|
| 416 |
+
|
| 417 |
+
bucket_iterators = {}
|
| 418 |
+
bucket_batches = {}
|
| 419 |
+
|
| 420 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 421 |
+
balanced_indices = self._create_balanced_indices(dataset_groups)
|
| 422 |
+
|
| 423 |
+
# Global shuffle before sharding (important for distributed consistency)
|
| 424 |
+
if self.shuffle:
|
| 425 |
+
perm = torch.randperm(len(balanced_indices), generator=self.generator).tolist()
|
| 426 |
+
balanced_indices = [balanced_indices[i] for i in perm]
|
| 427 |
+
|
| 428 |
+
# Shard indices for this SP group
|
| 429 |
+
sp_group_indices = self._shard_indices_for_sp_group(balanced_indices)
|
| 430 |
+
|
| 431 |
+
batches = []
|
| 432 |
+
for i in range(0, len(sp_group_indices), self.batch_size):
|
| 433 |
+
batch = sp_group_indices[i : i + self.batch_size]
|
| 434 |
+
if len(batch) == self.batch_size or not self.drop_last:
|
| 435 |
+
batches.append(batch)
|
| 436 |
+
|
| 437 |
+
if batches:
|
| 438 |
+
bucket_batches[bucket_key] = batches
|
| 439 |
+
bucket_iterators[bucket_key] = iter(batches)
|
| 440 |
+
|
| 441 |
+
remaining_buckets = list(bucket_iterators.keys())
|
| 442 |
+
|
| 443 |
+
while remaining_buckets:
|
| 444 |
+
idx = torch.randint(len(remaining_buckets), (1,), generator=self.generator).item()
|
| 445 |
+
bucket_key = remaining_buckets[idx]
|
| 446 |
+
bucket_iter = bucket_iterators[bucket_key]
|
| 447 |
+
|
| 448 |
+
try:
|
| 449 |
+
batch = next(bucket_iter)
|
| 450 |
+
yield batch
|
| 451 |
+
except StopIteration:
|
| 452 |
+
remaining_buckets.remove(bucket_key)
|
| 453 |
+
|
| 454 |
+
def _create_balanced_indices(self, dataset_groups):
|
| 455 |
+
return sum(dataset_groups.values(), [])
|
| 456 |
+
|
| 457 |
+
def _equal_sampling(self, dataset_groups):
|
| 458 |
+
all_indices = []
|
| 459 |
+
dataset_names = list(dataset_groups.keys())
|
| 460 |
+
|
| 461 |
+
if len(dataset_names) <= 1:
|
| 462 |
+
return sum(dataset_groups.values(), [])
|
| 463 |
+
|
| 464 |
+
min_samples = min(len(indices) for indices in dataset_groups.values())
|
| 465 |
+
|
| 466 |
+
for dataset_name, indices in dataset_groups.items():
|
| 467 |
+
if len(indices) > min_samples:
|
| 468 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:min_samples].tolist()
|
| 469 |
+
sampled_indices = [indices[i] for i in selected]
|
| 470 |
+
else:
|
| 471 |
+
sampled_indices = indices
|
| 472 |
+
all_indices.extend(sampled_indices)
|
| 473 |
+
|
| 474 |
+
return all_indices
|
| 475 |
+
|
| 476 |
+
def _ratio_sampling(self, dataset_groups):
|
| 477 |
+
return sum(dataset_groups.values(), [])
|
| 478 |
+
|
| 479 |
+
def __len__(self):
|
| 480 |
+
if self.dataset_sampling_ratios:
|
| 481 |
+
temp_generator = torch.Generator()
|
| 482 |
+
temp_generator.manual_seed(self.seed)
|
| 483 |
+
|
| 484 |
+
dataset_sample_map = {}
|
| 485 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 486 |
+
for dataset_name, indices in dataset_groups.items():
|
| 487 |
+
if dataset_name not in dataset_sample_map:
|
| 488 |
+
dataset_sample_map[dataset_name] = []
|
| 489 |
+
dataset_sample_map[dataset_name].extend(indices)
|
| 490 |
+
|
| 491 |
+
total_samples = sum(len(indices) for indices in dataset_sample_map.values())
|
| 492 |
+
total_ratio = sum(self.dataset_sampling_ratios.values())
|
| 493 |
+
|
| 494 |
+
sampled_total = 0
|
| 495 |
+
for dataset_name, indices in dataset_sample_map.items():
|
| 496 |
+
if dataset_name in self.dataset_sampling_ratios:
|
| 497 |
+
ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio
|
| 498 |
+
target_samples = max(1, int(total_samples * ratio))
|
| 499 |
+
sampled_total += target_samples
|
| 500 |
+
else:
|
| 501 |
+
sampled_total += len(indices)
|
| 502 |
+
|
| 503 |
+
# Account for SP group sharding
|
| 504 |
+
sp_group_samples = sampled_total // self.num_sp_groups
|
| 505 |
+
if not self.drop_last and sampled_total % self.num_sp_groups != 0:
|
| 506 |
+
sp_group_samples += 1
|
| 507 |
+
|
| 508 |
+
total_batches = sp_group_samples // self.batch_size
|
| 509 |
+
if not self.drop_last and sp_group_samples % self.batch_size != 0:
|
| 510 |
+
total_batches += 1
|
| 511 |
+
return total_batches
|
| 512 |
+
else:
|
| 513 |
+
total_batches = 0
|
| 514 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 515 |
+
balanced_indices = self._create_balanced_indices(dataset_groups)
|
| 516 |
+
|
| 517 |
+
# Account for SP group sharding
|
| 518 |
+
sp_group_size = len(balanced_indices) // self.num_sp_groups
|
| 519 |
+
if not self.drop_last and len(balanced_indices) % self.num_sp_groups != 0:
|
| 520 |
+
sp_group_size += 1
|
| 521 |
+
|
| 522 |
+
num_batches = sp_group_size // self.batch_size
|
| 523 |
+
if not self.drop_last and sp_group_size % self.batch_size != 0:
|
| 524 |
+
num_batches += 1
|
| 525 |
+
total_batches += num_batches
|
| 526 |
+
return total_batches
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def collate_fn(batch):
|
| 530 |
+
return {
|
| 531 |
+
key: torch.stack([d[key] for d in batch])
|
| 532 |
+
if isinstance(batch[0][key], torch.Tensor)
|
| 533 |
+
else [d[key] for d in batch]
|
| 534 |
+
for key in batch[0]
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
if __name__ == "__main__":
|
| 539 |
+
import torch.distributed.checkpoint as dcp
|
| 540 |
+
from accelerate import Accelerator
|
| 541 |
+
from torchdata.stateful_dataloader import StatefulDataLoader
|
| 542 |
+
|
| 543 |
+
feature_folder = [
|
| 544 |
+
"demo_data/ultravideo-long",
|
| 545 |
+
]
|
| 546 |
+
dataloader_num_workers = 0
|
| 547 |
+
batch_size = 2
|
| 548 |
+
num_train_epochs = 2
|
| 549 |
+
seed = 0
|
| 550 |
+
output_dir = "accelerate_checkpoints"
|
| 551 |
+
checkpoint_dirs = (
|
| 552 |
+
[
|
| 553 |
+
d
|
| 554 |
+
for d in os.listdir(output_dir)
|
| 555 |
+
if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d))
|
| 556 |
+
]
|
| 557 |
+
if os.path.exists(output_dir)
|
| 558 |
+
else []
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
dataset_ratios = {}
|
| 562 |
+
# dataset_ratios = {
|
| 563 |
+
# "demo_data/ultravideo-long": 0.9,
|
| 564 |
+
# }
|
| 565 |
+
|
| 566 |
+
accelerator = Accelerator()
|
| 567 |
+
print(accelerator.process_index, accelerator.num_processes)
|
| 568 |
+
|
| 569 |
+
dataset = BucketedFeatureDataset(
|
| 570 |
+
feature_folder,
|
| 571 |
+
force_rebuild=True,
|
| 572 |
+
return_all_vae_latent=True,
|
| 573 |
+
return_prompt_raw=True,
|
| 574 |
+
single_res=True,
|
| 575 |
+
single_height=384,
|
| 576 |
+
single_width=640,
|
| 577 |
+
seed=seed,
|
| 578 |
+
)
|
| 579 |
+
sampler = BucketedSampler(
|
| 580 |
+
dataset,
|
| 581 |
+
batch_size=batch_size,
|
| 582 |
+
drop_last=True,
|
| 583 |
+
shuffle=True,
|
| 584 |
+
dataset_sampling_ratios=dataset_ratios,
|
| 585 |
+
seed=seed,
|
| 586 |
+
# num_sp_groups=get_world_size() // get_sp_world_size(),
|
| 587 |
+
# sp_world_size=get_sp_world_size(),
|
| 588 |
+
# global_rank=get_world_rank(),
|
| 589 |
+
num_sp_groups=accelerator.num_processes // 1,
|
| 590 |
+
sp_world_size=1,
|
| 591 |
+
global_rank=accelerator.process_index,
|
| 592 |
+
)
|
| 593 |
+
dataloader = StatefulDataLoader(
|
| 594 |
+
dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=dataloader_num_workers
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
print(len(dataset), len(dataloader))
|
| 598 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 599 |
+
|
| 600 |
+
step = 0
|
| 601 |
+
global_step = 0
|
| 602 |
+
first_epoch = 0
|
| 603 |
+
num_update_steps_per_epoch = len(dataloader)
|
| 604 |
+
if checkpoint_dirs:
|
| 605 |
+
latest_checkpoint = max(checkpoint_dirs, key=lambda x: int(x.split("-")[1]))
|
| 606 |
+
checkpoint_path = os.path.join(output_dir, latest_checkpoint)
|
| 607 |
+
print(f"Found checkpoint: {checkpoint_path}")
|
| 608 |
+
|
| 609 |
+
accelerator.load_state(checkpoint_path)
|
| 610 |
+
global_step = int(latest_checkpoint.split("-")[1])
|
| 611 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 612 |
+
|
| 613 |
+
states = {
|
| 614 |
+
"dataloader": dataloader,
|
| 615 |
+
}
|
| 616 |
+
dcp_dir = os.path.join(checkpoint_path, "distributed_checkpoint")
|
| 617 |
+
dcp.load(states, checkpoint_id=dcp_dir)
|
| 618 |
+
|
| 619 |
+
print(f"Resuming from step {global_step}, epoch {first_epoch}")
|
| 620 |
+
|
| 621 |
+
print("Testing dataloader...")
|
| 622 |
+
step = global_step
|
| 623 |
+
dataset_counts = defaultdict(int)
|
| 624 |
+
for epoch in range(first_epoch, num_train_epochs):
|
| 625 |
+
sampler.set_epoch(epoch)
|
| 626 |
+
dataset.set_epoch(epoch)
|
| 627 |
+
for i, batch in enumerate(dataloader):
|
| 628 |
+
# Get metadata
|
| 629 |
+
uttid = batch["uttid"]
|
| 630 |
+
num_frame = batch["num_frame"]
|
| 631 |
+
height = batch["height"]
|
| 632 |
+
width = batch["width"]
|
| 633 |
+
bucket_key = batch["bucket_key"]
|
| 634 |
+
|
| 635 |
+
# Get feature
|
| 636 |
+
x0_latents = batch["x0_latents"]
|
| 637 |
+
history_latents = batch["history_latents"]
|
| 638 |
+
target_latents = batch["target_latents"]
|
| 639 |
+
prompt_embeds = batch["prompt_embeds"]
|
| 640 |
+
|
| 641 |
+
if accelerator.process_index == 0:
|
| 642 |
+
# print info
|
| 643 |
+
print(f" Step {step}:")
|
| 644 |
+
print(f" Batch {i}:")
|
| 645 |
+
# print(f" Data Name: {batch['dataset_name']}")
|
| 646 |
+
print(f" Batch size: {len(uttid)}")
|
| 647 |
+
print(f" Uttids: {uttid}")
|
| 648 |
+
print(f" Dimensions - frames: {num_frame[0]}, height: {height[0]}, width: {width[0]}")
|
| 649 |
+
print(f" Bucket key: {bucket_key[0]}")
|
| 650 |
+
print(f" X0 latent shape: {x0_latents.shape}")
|
| 651 |
+
print(f" History latent shape: {history_latents.shape}")
|
| 652 |
+
print(f" Context latent shape: {target_latents.shape}")
|
| 653 |
+
print(f" Prompt embed shape: {prompt_embeds.shape}")
|
| 654 |
+
# print(f" Prompt attention mask shape: {prompt_attention_masks.shape}")
|
| 655 |
+
|
| 656 |
+
# verify
|
| 657 |
+
assert all(nf == num_frame[0] for nf in num_frame), "Frame numbers not consistent in batch"
|
| 658 |
+
assert all(h == height[0] for h in height), "Heights not consistent in batch"
|
| 659 |
+
assert all(w == width[0] for w in width), "Widths not consistent in batch"
|
| 660 |
+
|
| 661 |
+
print(" ✓ Batch dimensions are consistent")
|
| 662 |
+
|
| 663 |
+
for dataset_name in batch["dataset_name"]:
|
| 664 |
+
dataset_counts[dataset_name] += 1
|
| 665 |
+
|
| 666 |
+
step += 1
|
| 667 |
+
|
| 668 |
+
# if step == 20:
|
| 669 |
+
# checkpoint_dir = f"checkpoint-{step}"
|
| 670 |
+
# save_path = os.path.join(output_dir, checkpoint_dir)
|
| 671 |
+
# os.makedirs(save_path, exist_ok=True)
|
| 672 |
+
|
| 673 |
+
# if accelerator.is_main_process:
|
| 674 |
+
# print(f"Saving checkpoint at step {step}")
|
| 675 |
+
|
| 676 |
+
# accelerator.save_state(save_path)
|
| 677 |
+
|
| 678 |
+
# print(accelerator.process_index, accelerator.num_processes)
|
| 679 |
+
# states = {
|
| 680 |
+
# "dataloader": dataloader,
|
| 681 |
+
# }
|
| 682 |
+
# dcp_dir = os.path.join(save_path, "distributed_checkpoint")
|
| 683 |
+
# dcp.save(states, checkpoint_id=dcp_dir)
|
| 684 |
+
|
| 685 |
+
print("实际采样统计:", dict(dataset_counts))
|
Helios/_DEV/helios/dataset/dataloader_mp4_dist.py
ADDED
|
@@ -0,0 +1,854 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import pickle
|
| 4 |
+
import random
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import torch
|
| 10 |
+
import torchvision
|
| 11 |
+
from torch.utils.data import Dataset, Sampler
|
| 12 |
+
from video_reader import PyVideoReader
|
| 13 |
+
|
| 14 |
+
from diffusers.training_utils import free_memory
|
| 15 |
+
from diffusers.utils import export_to_video
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
resolution_bucket_options = {
|
| 19 |
+
640: [
|
| 20 |
+
(768, 320),
|
| 21 |
+
(768, 384),
|
| 22 |
+
(640, 384),
|
| 23 |
+
(768, 512),
|
| 24 |
+
(576, 448),
|
| 25 |
+
(512, 512),
|
| 26 |
+
(448, 576),
|
| 27 |
+
(512, 768),
|
| 28 |
+
(384, 640),
|
| 29 |
+
(384, 768),
|
| 30 |
+
(320, 768),
|
| 31 |
+
],
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
length_bucket_options = {
|
| 35 |
+
1: [
|
| 36 |
+
501,
|
| 37 |
+
481,
|
| 38 |
+
461,
|
| 39 |
+
441,
|
| 40 |
+
421,
|
| 41 |
+
401,
|
| 42 |
+
381,
|
| 43 |
+
361,
|
| 44 |
+
341,
|
| 45 |
+
321,
|
| 46 |
+
301,
|
| 47 |
+
281,
|
| 48 |
+
261,
|
| 49 |
+
241,
|
| 50 |
+
221,
|
| 51 |
+
193,
|
| 52 |
+
181,
|
| 53 |
+
161,
|
| 54 |
+
141,
|
| 55 |
+
121,
|
| 56 |
+
101,
|
| 57 |
+
81,
|
| 58 |
+
61,
|
| 59 |
+
41,
|
| 60 |
+
21,
|
| 61 |
+
],
|
| 62 |
+
2: [193, 177, 161, 156, 145, 133, 129, 121, 113, 109, 97, 85, 81, 73, 65, 61, 49, 37, 25],
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def find_nearest_resolution_bucket(h, w, resolution=640):
|
| 67 |
+
min_metric = float("inf")
|
| 68 |
+
best_bucket = None
|
| 69 |
+
for bucket_h, bucket_w in resolution_bucket_options[resolution]:
|
| 70 |
+
metric = abs(h * bucket_w - w * bucket_h)
|
| 71 |
+
if metric <= min_metric:
|
| 72 |
+
min_metric = metric
|
| 73 |
+
best_bucket = (bucket_h, bucket_w)
|
| 74 |
+
return best_bucket
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def find_nearest_length_bucket(length, stride=1):
|
| 78 |
+
buckets = length_bucket_options[stride]
|
| 79 |
+
min_bucket = min(buckets)
|
| 80 |
+
if length < min_bucket:
|
| 81 |
+
return length
|
| 82 |
+
valid_buckets = [bucket for bucket in buckets if bucket <= length]
|
| 83 |
+
return max(valid_buckets)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def read_cut_crop_and_resize(
|
| 87 |
+
video_path, f_prime, h_prime, w_prime, stride=1, start_frame=None, end_frame=None, crop=None
|
| 88 |
+
):
|
| 89 |
+
frame_indices = list(range(start_frame, end_frame, stride))
|
| 90 |
+
assert len(frame_indices) == f_prime
|
| 91 |
+
|
| 92 |
+
vr = PyVideoReader(video_path, threads=0) # 0 means auto (let ffmpeg pick the optimal number)
|
| 93 |
+
frames = torch.from_numpy(vr.get_batch(frame_indices)).float()
|
| 94 |
+
|
| 95 |
+
frames = (frames / 127.5) - 1
|
| 96 |
+
video = frames.permute(0, 3, 1, 2)
|
| 97 |
+
|
| 98 |
+
s_x, e_x, s_y, e_y = crop
|
| 99 |
+
video = video[:, :, s_y:e_y, s_x:e_x]
|
| 100 |
+
|
| 101 |
+
frames, channels, h, w = video.shape
|
| 102 |
+
aspect_ratio_original = h / w
|
| 103 |
+
aspect_ratio_target = h_prime / w_prime
|
| 104 |
+
|
| 105 |
+
if aspect_ratio_original >= aspect_ratio_target:
|
| 106 |
+
new_h = int(w * aspect_ratio_target)
|
| 107 |
+
top = (h - new_h) // 2
|
| 108 |
+
bottom = top + new_h
|
| 109 |
+
left = 0
|
| 110 |
+
right = w
|
| 111 |
+
else:
|
| 112 |
+
new_w = int(h / aspect_ratio_target)
|
| 113 |
+
left = (w - new_w) // 2
|
| 114 |
+
right = left + new_w
|
| 115 |
+
top = 0
|
| 116 |
+
bottom = h
|
| 117 |
+
|
| 118 |
+
# Crop the video
|
| 119 |
+
cropped_video = video[:, :, top:bottom, left:right]
|
| 120 |
+
# Resize the cropped video
|
| 121 |
+
resized_video = torchvision.transforms.functional.resize(cropped_video, (h_prime, w_prime))
|
| 122 |
+
return resized_video
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def save_frames(frame_raw, fps=24, video_path="1.mp4"):
|
| 126 |
+
save_list = []
|
| 127 |
+
for frame in frame_raw:
|
| 128 |
+
frame = (frame + 1) / 2 * 255
|
| 129 |
+
frame = torchvision.transforms.transforms.ToPILImage()(frame.to(torch.uint8)).convert("RGB")
|
| 130 |
+
save_list.append(frame)
|
| 131 |
+
frame = None
|
| 132 |
+
del frame
|
| 133 |
+
export_to_video(save_list, video_path, fps=fps)
|
| 134 |
+
|
| 135 |
+
save_list = None
|
| 136 |
+
del save_list
|
| 137 |
+
free_memory()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class BucketedFeatureDataset(Dataset):
|
| 141 |
+
def __init__(
|
| 142 |
+
self,
|
| 143 |
+
json_files,
|
| 144 |
+
video_folders,
|
| 145 |
+
stride=1,
|
| 146 |
+
base_fps=None,
|
| 147 |
+
resolution=640,
|
| 148 |
+
force_rebuild=True,
|
| 149 |
+
single_res=False,
|
| 150 |
+
single_length=False,
|
| 151 |
+
single_num_frame=81,
|
| 152 |
+
single_height=384,
|
| 153 |
+
single_width=640,
|
| 154 |
+
multi_res=False,
|
| 155 |
+
id_token: Optional[str] = None,
|
| 156 |
+
):
|
| 157 |
+
self.stride = stride
|
| 158 |
+
self.base_fps = base_fps
|
| 159 |
+
self.resolution = resolution
|
| 160 |
+
self.force_rebuild = force_rebuild
|
| 161 |
+
self.single_res = single_res
|
| 162 |
+
self.single_height = single_height
|
| 163 |
+
self.single_width = single_width
|
| 164 |
+
self.single_length = single_length
|
| 165 |
+
self.single_num_frame = single_num_frame
|
| 166 |
+
self.multi_res = multi_res
|
| 167 |
+
self.id_token = id_token or ""
|
| 168 |
+
self._epoch = 0
|
| 169 |
+
|
| 170 |
+
if isinstance(json_files, str):
|
| 171 |
+
self.json_files = [json_files]
|
| 172 |
+
else:
|
| 173 |
+
self.json_files = json_files
|
| 174 |
+
|
| 175 |
+
if isinstance(video_folders, str):
|
| 176 |
+
self.video_folders = [video_folders]
|
| 177 |
+
else:
|
| 178 |
+
self.video_folders = video_folders
|
| 179 |
+
|
| 180 |
+
assert len(self.json_files) == len(self.video_folders), (
|
| 181 |
+
f"json_files ({len(self.json_files)}) and video_folders ({len(self.video_folders)}) must have the same length"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
self.samples = []
|
| 185 |
+
self.buckets = defaultdict(list)
|
| 186 |
+
|
| 187 |
+
for json_file, video_folder in zip(self.json_files, self.video_folders):
|
| 188 |
+
cache_file = json_file.replace(".json", "_cache.pkl").replace(".csv", "_cache.pkl")
|
| 189 |
+
self._process_json_file(json_file, video_folder, cache_file)
|
| 190 |
+
|
| 191 |
+
def _process_json_file(self, json_file, video_folder, cache_file):
|
| 192 |
+
if self.force_rebuild or not os.path.exists(cache_file):
|
| 193 |
+
if os.path.exists(cache_file):
|
| 194 |
+
print(f"Remove {cache_file}")
|
| 195 |
+
os.remove(cache_file)
|
| 196 |
+
print(f"Building metadata cache for file: {json_file}")
|
| 197 |
+
print(f" Video folder: {video_folder}")
|
| 198 |
+
file_samples, file_buckets = self._build_file_metadata(json_file, video_folder)
|
| 199 |
+
|
| 200 |
+
print(f"Saving metadata cache to: {cache_file}")
|
| 201 |
+
cached_data = {"samples": file_samples, "buckets": file_buckets}
|
| 202 |
+
with open(cache_file, "wb") as f:
|
| 203 |
+
pickle.dump(cached_data, f)
|
| 204 |
+
print(f"Cached {len(file_samples)} samples from {json_file}\n")
|
| 205 |
+
else:
|
| 206 |
+
print(f"Loading cached metadata from: {cache_file}")
|
| 207 |
+
with open(cache_file, "rb") as f:
|
| 208 |
+
cached_data = pickle.load(f)
|
| 209 |
+
file_samples = cached_data["samples"]
|
| 210 |
+
file_buckets = cached_data["buckets"]
|
| 211 |
+
print(f"Loaded {len(file_samples)} samples from cache: {cache_file}\n")
|
| 212 |
+
|
| 213 |
+
sample_idx_offset = len(self.samples)
|
| 214 |
+
self.samples.extend(file_samples)
|
| 215 |
+
|
| 216 |
+
for bucket_key, indices in file_buckets.items():
|
| 217 |
+
adjusted_indices = [idx + sample_idx_offset for idx in indices]
|
| 218 |
+
self.buckets[bucket_key].extend(adjusted_indices)
|
| 219 |
+
|
| 220 |
+
def _build_file_metadata(self, json_file, video_folder):
|
| 221 |
+
with open(json_file, "r") as f:
|
| 222 |
+
data = json.load(f)
|
| 223 |
+
|
| 224 |
+
print(f"Scanning video folder: {video_folder}")
|
| 225 |
+
existing_videos = set()
|
| 226 |
+
for root, dirs, files in os.walk(video_folder):
|
| 227 |
+
for file in files:
|
| 228 |
+
if file.endswith(".mp4"):
|
| 229 |
+
rel_path = os.path.relpath(os.path.join(root, file), video_folder)
|
| 230 |
+
existing_videos.add(rel_path)
|
| 231 |
+
print(f"Found {len(existing_videos)} video files")
|
| 232 |
+
|
| 233 |
+
df = pd.DataFrame(
|
| 234 |
+
[
|
| 235 |
+
{
|
| 236 |
+
"cut": item["cut"],
|
| 237 |
+
"crop": item["crop"],
|
| 238 |
+
"path": item["path"],
|
| 239 |
+
"num_frames": item["num_frames"],
|
| 240 |
+
"width": item["resolution"]["width"],
|
| 241 |
+
"height": item["resolution"]["height"],
|
| 242 |
+
"fps": item["fps"],
|
| 243 |
+
"cap": item["cap"],
|
| 244 |
+
}
|
| 245 |
+
for item in data
|
| 246 |
+
]
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
samples = []
|
| 250 |
+
buckets = defaultdict(list)
|
| 251 |
+
sample_idx = 0
|
| 252 |
+
|
| 253 |
+
print(f"Processing {len(df)} records from {json_file} with stride={self.stride}...")
|
| 254 |
+
for i, row in df.iterrows():
|
| 255 |
+
if i % 10000 == 0:
|
| 256 |
+
print(f" Processed {i}/{len(df)} records")
|
| 257 |
+
|
| 258 |
+
video_file = (
|
| 259 |
+
row["path"]
|
| 260 |
+
.replace("videos_clip_v1_20241111/", "")
|
| 261 |
+
.replace("videos_clip_v2_20241111/", "")
|
| 262 |
+
.replace("videos_clip_v4_20241111/", "")
|
| 263 |
+
)
|
| 264 |
+
if video_file not in existing_videos:
|
| 265 |
+
print("bad video!")
|
| 266 |
+
continue
|
| 267 |
+
video_path = os.path.join(video_folder, video_file)
|
| 268 |
+
|
| 269 |
+
cut_start_frame = row["cut"][0]
|
| 270 |
+
cut_end_frame = row["cut"][1]
|
| 271 |
+
num_frame = cut_end_frame - cut_start_frame
|
| 272 |
+
|
| 273 |
+
if self.single_length:
|
| 274 |
+
if num_frame < self.single_num_frame:
|
| 275 |
+
continue
|
| 276 |
+
else:
|
| 277 |
+
if num_frame < 121:
|
| 278 |
+
continue
|
| 279 |
+
|
| 280 |
+
uttid = os.path.basename(video_file).replace(".mp4", "") + f"_{cut_start_frame}-{cut_end_frame}"
|
| 281 |
+
fps = row["fps"]
|
| 282 |
+
|
| 283 |
+
crop = row["crop"]
|
| 284 |
+
width = crop[1] - crop[0]
|
| 285 |
+
height = crop[3] - crop[2]
|
| 286 |
+
|
| 287 |
+
prompt = row["cap"][0]
|
| 288 |
+
|
| 289 |
+
# TODO need to be checked
|
| 290 |
+
effective_num_frame = (num_frame + self.stride - 1) // self.stride
|
| 291 |
+
bucket_num_frame = find_nearest_length_bucket(effective_num_frame, stride=self.stride)
|
| 292 |
+
bucket_height, bucket_width = find_nearest_resolution_bucket(height, width, resolution=self.resolution)
|
| 293 |
+
|
| 294 |
+
if self.single_res or self.multi_res:
|
| 295 |
+
allowed_resolutions = [(self.single_height, self.single_width)]
|
| 296 |
+
if self.multi_res:
|
| 297 |
+
allowed_resolutions.extend(
|
| 298 |
+
[
|
| 299 |
+
(self.single_height // 2, self.single_width // 2),
|
| 300 |
+
(self.single_height // 4, self.single_width // 4),
|
| 301 |
+
]
|
| 302 |
+
)
|
| 303 |
+
if (bucket_height, bucket_width) not in allowed_resolutions:
|
| 304 |
+
print("continue res")
|
| 305 |
+
continue
|
| 306 |
+
bucket_height, bucket_width = random.choice(allowed_resolutions)
|
| 307 |
+
|
| 308 |
+
if self.single_length:
|
| 309 |
+
bucket_num_frame = self.single_num_frame
|
| 310 |
+
|
| 311 |
+
if self.base_fps is not None:
|
| 312 |
+
stride = max(int(fps / self.base_fps), 1)
|
| 313 |
+
required_frames = bucket_num_frame * stride
|
| 314 |
+
if required_frames >= num_frame:
|
| 315 |
+
print("continue frame")
|
| 316 |
+
continue
|
| 317 |
+
else:
|
| 318 |
+
stride = self.stride
|
| 319 |
+
|
| 320 |
+
bucket_key = (bucket_num_frame, bucket_height, bucket_width)
|
| 321 |
+
|
| 322 |
+
sample_info = {
|
| 323 |
+
"uttid": uttid,
|
| 324 |
+
"dataset_name": json_file.rstrip("/"),
|
| 325 |
+
"video_folder": video_folder,
|
| 326 |
+
"video_path": video_path,
|
| 327 |
+
"bucket_key": bucket_key,
|
| 328 |
+
"prompt": self.id_token + prompt,
|
| 329 |
+
"fps": fps,
|
| 330 |
+
"stride": stride,
|
| 331 |
+
"effective_num_frame": effective_num_frame,
|
| 332 |
+
"num_frame": num_frame,
|
| 333 |
+
"height": height,
|
| 334 |
+
"width": width,
|
| 335 |
+
"bucket_num_frame": bucket_num_frame,
|
| 336 |
+
"bucket_height": bucket_height,
|
| 337 |
+
"bucket_width": bucket_width,
|
| 338 |
+
"cut_start_frame": cut_start_frame,
|
| 339 |
+
"cut_end_frame": cut_end_frame,
|
| 340 |
+
"crop": crop,
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
samples.append(sample_info)
|
| 344 |
+
buckets[bucket_key].append(sample_idx)
|
| 345 |
+
sample_idx += 1
|
| 346 |
+
|
| 347 |
+
return samples, buckets
|
| 348 |
+
|
| 349 |
+
def set_epoch(self, epoch):
|
| 350 |
+
self._epoch = epoch
|
| 351 |
+
|
| 352 |
+
def __len__(self):
|
| 353 |
+
return len(self.samples)
|
| 354 |
+
|
| 355 |
+
def __getitem__(self, idx):
|
| 356 |
+
anchor_h = self.samples[idx]["bucket_height"]
|
| 357 |
+
anchor_w = self.samples[idx]["bucket_width"]
|
| 358 |
+
anchor_f = self.samples[idx]["bucket_num_frame"]
|
| 359 |
+
|
| 360 |
+
max_retries = 1000
|
| 361 |
+
retry_count = 0
|
| 362 |
+
|
| 363 |
+
while retry_count < max_retries:
|
| 364 |
+
sample_info = self.samples[idx]
|
| 365 |
+
|
| 366 |
+
if (
|
| 367 |
+
anchor_h != sample_info["bucket_height"]
|
| 368 |
+
or anchor_w != sample_info["bucket_width"]
|
| 369 |
+
or anchor_f != sample_info["bucket_num_frame"]
|
| 370 |
+
):
|
| 371 |
+
idx = random.randint(0, len(self.samples) - 1)
|
| 372 |
+
retry_count += 1
|
| 373 |
+
continue
|
| 374 |
+
|
| 375 |
+
try:
|
| 376 |
+
stride = sample_info["stride"]
|
| 377 |
+
cut_start_frame = sample_info["cut_start_frame"]
|
| 378 |
+
cut_end_frame = sample_info["cut_end_frame"]
|
| 379 |
+
bucket_num_frame = sample_info["bucket_num_frame"]
|
| 380 |
+
|
| 381 |
+
max_start_frame = cut_end_frame - bucket_num_frame * stride
|
| 382 |
+
if max_start_frame < cut_start_frame:
|
| 383 |
+
start_frame = cut_start_frame
|
| 384 |
+
else:
|
| 385 |
+
start_frame = random.randint(cut_start_frame, max_start_frame)
|
| 386 |
+
end_frame = start_frame + bucket_num_frame * stride
|
| 387 |
+
|
| 388 |
+
video_data = read_cut_crop_and_resize(
|
| 389 |
+
video_path=sample_info["video_path"],
|
| 390 |
+
f_prime=sample_info["bucket_num_frame"],
|
| 391 |
+
h_prime=sample_info["bucket_height"],
|
| 392 |
+
w_prime=sample_info["bucket_width"],
|
| 393 |
+
stride=stride,
|
| 394 |
+
start_frame=start_frame,
|
| 395 |
+
end_frame=end_frame,
|
| 396 |
+
crop=sample_info["crop"],
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
return {
|
| 400 |
+
"uttid": sample_info["uttid"],
|
| 401 |
+
"bucket_key": sample_info["bucket_key"],
|
| 402 |
+
"dataset_name": sample_info["dataset_name"],
|
| 403 |
+
"video_metadata": {
|
| 404 |
+
"num_frames": sample_info["bucket_num_frame"],
|
| 405 |
+
"height": sample_info["bucket_height"],
|
| 406 |
+
"width": sample_info["bucket_width"],
|
| 407 |
+
"fps": sample_info["fps"],
|
| 408 |
+
"stride": stride,
|
| 409 |
+
"effective_num_frame": sample_info["effective_num_frame"],
|
| 410 |
+
},
|
| 411 |
+
"videos": video_data,
|
| 412 |
+
"prompts": sample_info["prompt"],
|
| 413 |
+
"first_frames_images": (video_data[0] + 1) / 2 * 255,
|
| 414 |
+
}
|
| 415 |
+
except Exception as e:
|
| 416 |
+
print(f"Error loading {sample_info['video_path']}: {e}")
|
| 417 |
+
idx = random.randint(0, len(self.samples) - 1)
|
| 418 |
+
retry_count += 1
|
| 419 |
+
|
| 420 |
+
print(f"Failed to load sample after {max_retries} retries, returning None")
|
| 421 |
+
return None
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class BucketedSampler(Sampler):
|
| 425 |
+
def __init__(
|
| 426 |
+
self,
|
| 427 |
+
dataset,
|
| 428 |
+
batch_size,
|
| 429 |
+
drop_last=False,
|
| 430 |
+
shuffle=True,
|
| 431 |
+
seed=42,
|
| 432 |
+
dataset_sampling_ratios=None,
|
| 433 |
+
num_sp_groups=1,
|
| 434 |
+
sp_world_size=1,
|
| 435 |
+
global_rank=0,
|
| 436 |
+
):
|
| 437 |
+
self.dataset = dataset
|
| 438 |
+
self.batch_size = batch_size
|
| 439 |
+
self.drop_last = drop_last
|
| 440 |
+
self.shuffle = shuffle
|
| 441 |
+
self.seed = seed
|
| 442 |
+
self.generator = torch.Generator()
|
| 443 |
+
self.buckets = dataset.buckets
|
| 444 |
+
self._epoch = 0
|
| 445 |
+
|
| 446 |
+
# Distributed parameters
|
| 447 |
+
self.num_sp_groups = num_sp_groups
|
| 448 |
+
self.sp_world_size = sp_world_size
|
| 449 |
+
self.global_rank = global_rank
|
| 450 |
+
self.ith_sp_group = self.global_rank // self.sp_world_size
|
| 451 |
+
|
| 452 |
+
self.dataset_sampling_ratios = (
|
| 453 |
+
{key.rstrip("/"): value for key, value in dataset_sampling_ratios.items()}
|
| 454 |
+
if dataset_sampling_ratios is not None
|
| 455 |
+
else {}
|
| 456 |
+
)
|
| 457 |
+
self._prepare_dataset_buckets()
|
| 458 |
+
|
| 459 |
+
def _prepare_dataset_buckets(self):
|
| 460 |
+
self.dataset_buckets = {}
|
| 461 |
+
|
| 462 |
+
for bucket_key, sample_indices in self.buckets.items():
|
| 463 |
+
dataset_groups = {}
|
| 464 |
+
for idx in sample_indices:
|
| 465 |
+
dataset_name = self.dataset.samples[idx]["dataset_name"]
|
| 466 |
+
if dataset_name not in dataset_groups:
|
| 467 |
+
dataset_groups[dataset_name] = []
|
| 468 |
+
dataset_groups[dataset_name].append(idx)
|
| 469 |
+
self.dataset_buckets[bucket_key] = dataset_groups
|
| 470 |
+
|
| 471 |
+
def set_epoch(self, epoch):
|
| 472 |
+
self._epoch = epoch
|
| 473 |
+
|
| 474 |
+
def _shard_indices_for_sp_group(self, indices):
|
| 475 |
+
"""
|
| 476 |
+
Shard indices across SP groups, similar to DP_SP_BatchSampler.
|
| 477 |
+
Each SP group gets a disjoint subset of the data.
|
| 478 |
+
"""
|
| 479 |
+
if self.num_sp_groups == 1:
|
| 480 |
+
return indices
|
| 481 |
+
|
| 482 |
+
# Convert to tensor if it's a list
|
| 483 |
+
if isinstance(indices, list):
|
| 484 |
+
indices_tensor = torch.tensor(indices, dtype=torch.long)
|
| 485 |
+
else:
|
| 486 |
+
indices_tensor = indices
|
| 487 |
+
|
| 488 |
+
# Pad indices if necessary to make it divisible by num_sp_groups
|
| 489 |
+
total_size = len(indices_tensor)
|
| 490 |
+
if total_size % self.num_sp_groups != 0:
|
| 491 |
+
if not self.drop_last:
|
| 492 |
+
padding_size = self.num_sp_groups - (total_size % self.num_sp_groups)
|
| 493 |
+
indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]])
|
| 494 |
+
else:
|
| 495 |
+
# If drop_last, truncate to be divisible
|
| 496 |
+
if self.drop_last:
|
| 497 |
+
truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups
|
| 498 |
+
indices_tensor = indices_tensor[:truncate_size]
|
| 499 |
+
|
| 500 |
+
# Shard: each SP group gets every num_sp_groups-th element
|
| 501 |
+
sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups]
|
| 502 |
+
|
| 503 |
+
return sp_group_indices.tolist()
|
| 504 |
+
|
| 505 |
+
def _apply_global_ratio_sampling(self):
|
| 506 |
+
if not self.dataset_sampling_ratios:
|
| 507 |
+
return
|
| 508 |
+
|
| 509 |
+
dataset_sample_map = {}
|
| 510 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 511 |
+
for dataset_name, indices in dataset_groups.items():
|
| 512 |
+
if dataset_name not in dataset_sample_map:
|
| 513 |
+
dataset_sample_map[dataset_name] = {"indices": [], "buckets": []}
|
| 514 |
+
dataset_sample_map[dataset_name]["indices"].extend(indices)
|
| 515 |
+
dataset_sample_map[dataset_name]["buckets"].extend([bucket_key] * len(indices))
|
| 516 |
+
|
| 517 |
+
total_samples = sum(len(info["indices"]) for info in dataset_sample_map.values())
|
| 518 |
+
total_ratio = sum(self.dataset_sampling_ratios.values())
|
| 519 |
+
|
| 520 |
+
sampled_dataset_map = {}
|
| 521 |
+
for dataset_name, info in dataset_sample_map.items():
|
| 522 |
+
if dataset_name in self.dataset_sampling_ratios:
|
| 523 |
+
ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio
|
| 524 |
+
target_samples = max(1, int(total_samples * ratio))
|
| 525 |
+
|
| 526 |
+
indices = info["indices"]
|
| 527 |
+
buckets = info["buckets"]
|
| 528 |
+
|
| 529 |
+
if len(indices) >= target_samples:
|
| 530 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:target_samples].tolist()
|
| 531 |
+
sampled_indices = [indices[i] for i in selected]
|
| 532 |
+
sampled_buckets = [buckets[i] for i in selected]
|
| 533 |
+
else:
|
| 534 |
+
sampled_indices = []
|
| 535 |
+
sampled_buckets = []
|
| 536 |
+
remaining = target_samples
|
| 537 |
+
|
| 538 |
+
while remaining > 0:
|
| 539 |
+
repeat_count = min(remaining, len(indices))
|
| 540 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:repeat_count].tolist()
|
| 541 |
+
sampled_indices.extend([indices[i] for i in selected])
|
| 542 |
+
sampled_buckets.extend([buckets[i] for i in selected])
|
| 543 |
+
remaining -= repeat_count
|
| 544 |
+
|
| 545 |
+
sampled_dataset_map[dataset_name] = {"indices": sampled_indices, "buckets": sampled_buckets}
|
| 546 |
+
else:
|
| 547 |
+
sampled_dataset_map[dataset_name] = info
|
| 548 |
+
|
| 549 |
+
new_dataset_buckets = {}
|
| 550 |
+
for bucket_key in self.dataset_buckets.keys():
|
| 551 |
+
new_dataset_buckets[bucket_key] = {}
|
| 552 |
+
|
| 553 |
+
for dataset_name, info in sampled_dataset_map.items():
|
| 554 |
+
indices = info["indices"]
|
| 555 |
+
buckets = info["buckets"]
|
| 556 |
+
|
| 557 |
+
for idx, bucket_key in zip(indices, buckets):
|
| 558 |
+
if dataset_name not in new_dataset_buckets[bucket_key]:
|
| 559 |
+
new_dataset_buckets[bucket_key][dataset_name] = []
|
| 560 |
+
new_dataset_buckets[bucket_key][dataset_name].append(idx)
|
| 561 |
+
|
| 562 |
+
self.dataset_buckets = new_dataset_buckets
|
| 563 |
+
|
| 564 |
+
def __iter__(self):
|
| 565 |
+
# Use epoch-level seed for reproducibility
|
| 566 |
+
epoch_seed = self.seed + self._epoch
|
| 567 |
+
self.generator.manual_seed(epoch_seed)
|
| 568 |
+
|
| 569 |
+
if self.dataset_sampling_ratios:
|
| 570 |
+
self._apply_global_ratio_sampling()
|
| 571 |
+
|
| 572 |
+
bucket_iterators = {}
|
| 573 |
+
bucket_batches = {}
|
| 574 |
+
|
| 575 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 576 |
+
balanced_indices = self._create_balanced_indices(dataset_groups)
|
| 577 |
+
|
| 578 |
+
# Global shuffle before sharding (important for distributed consistency)
|
| 579 |
+
if self.shuffle:
|
| 580 |
+
perm = torch.randperm(len(balanced_indices), generator=self.generator).tolist()
|
| 581 |
+
balanced_indices = [balanced_indices[i] for i in perm]
|
| 582 |
+
|
| 583 |
+
# Shard indices for this SP group
|
| 584 |
+
sp_group_indices = self._shard_indices_for_sp_group(balanced_indices)
|
| 585 |
+
|
| 586 |
+
batches = []
|
| 587 |
+
for i in range(0, len(sp_group_indices), self.batch_size):
|
| 588 |
+
batch = sp_group_indices[i : i + self.batch_size]
|
| 589 |
+
if len(batch) == self.batch_size or not self.drop_last:
|
| 590 |
+
batches.append(batch)
|
| 591 |
+
|
| 592 |
+
if batches:
|
| 593 |
+
bucket_batches[bucket_key] = batches
|
| 594 |
+
bucket_iterators[bucket_key] = iter(batches)
|
| 595 |
+
|
| 596 |
+
remaining_buckets = list(bucket_iterators.keys())
|
| 597 |
+
|
| 598 |
+
while remaining_buckets:
|
| 599 |
+
idx = torch.randint(len(remaining_buckets), (1,), generator=self.generator).item()
|
| 600 |
+
bucket_key = remaining_buckets[idx]
|
| 601 |
+
bucket_iter = bucket_iterators[bucket_key]
|
| 602 |
+
|
| 603 |
+
try:
|
| 604 |
+
batch = next(bucket_iter)
|
| 605 |
+
yield batch
|
| 606 |
+
except StopIteration:
|
| 607 |
+
remaining_buckets.remove(bucket_key)
|
| 608 |
+
|
| 609 |
+
def _create_balanced_indices(self, dataset_groups):
|
| 610 |
+
return sum(dataset_groups.values(), [])
|
| 611 |
+
|
| 612 |
+
def _equal_sampling(self, dataset_groups):
|
| 613 |
+
all_indices = []
|
| 614 |
+
dataset_names = list(dataset_groups.keys())
|
| 615 |
+
|
| 616 |
+
if len(dataset_names) <= 1:
|
| 617 |
+
return sum(dataset_groups.values(), [])
|
| 618 |
+
|
| 619 |
+
min_samples = min(len(indices) for indices in dataset_groups.values())
|
| 620 |
+
|
| 621 |
+
for dataset_name, indices in dataset_groups.items():
|
| 622 |
+
if len(indices) > min_samples:
|
| 623 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:min_samples].tolist()
|
| 624 |
+
sampled_indices = [indices[i] for i in selected]
|
| 625 |
+
else:
|
| 626 |
+
sampled_indices = indices
|
| 627 |
+
all_indices.extend(sampled_indices)
|
| 628 |
+
|
| 629 |
+
return all_indices
|
| 630 |
+
|
| 631 |
+
def _ratio_sampling(self, dataset_groups):
|
| 632 |
+
return sum(dataset_groups.values(), [])
|
| 633 |
+
|
| 634 |
+
def __len__(self):
|
| 635 |
+
if self.dataset_sampling_ratios:
|
| 636 |
+
temp_generator = torch.Generator()
|
| 637 |
+
temp_generator.manual_seed(self.seed)
|
| 638 |
+
|
| 639 |
+
dataset_sample_map = {}
|
| 640 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 641 |
+
for dataset_name, indices in dataset_groups.items():
|
| 642 |
+
if dataset_name not in dataset_sample_map:
|
| 643 |
+
dataset_sample_map[dataset_name] = []
|
| 644 |
+
dataset_sample_map[dataset_name].extend(indices)
|
| 645 |
+
|
| 646 |
+
total_samples = sum(len(indices) for indices in dataset_sample_map.values())
|
| 647 |
+
total_ratio = sum(self.dataset_sampling_ratios.values())
|
| 648 |
+
|
| 649 |
+
sampled_total = 0
|
| 650 |
+
for dataset_name, indices in dataset_sample_map.items():
|
| 651 |
+
if dataset_name in self.dataset_sampling_ratios:
|
| 652 |
+
ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio
|
| 653 |
+
target_samples = max(1, int(total_samples * ratio))
|
| 654 |
+
sampled_total += target_samples
|
| 655 |
+
else:
|
| 656 |
+
sampled_total += len(indices)
|
| 657 |
+
|
| 658 |
+
# Account for SP group sharding
|
| 659 |
+
sp_group_samples = sampled_total // self.num_sp_groups
|
| 660 |
+
if not self.drop_last and sampled_total % self.num_sp_groups != 0:
|
| 661 |
+
sp_group_samples += 1
|
| 662 |
+
|
| 663 |
+
total_batches = sp_group_samples // self.batch_size
|
| 664 |
+
if not self.drop_last and sp_group_samples % self.batch_size != 0:
|
| 665 |
+
total_batches += 1
|
| 666 |
+
return total_batches
|
| 667 |
+
else:
|
| 668 |
+
total_batches = 0
|
| 669 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 670 |
+
balanced_indices = self._create_balanced_indices(dataset_groups)
|
| 671 |
+
|
| 672 |
+
# Account for SP group sharding
|
| 673 |
+
sp_group_size = len(balanced_indices) // self.num_sp_groups
|
| 674 |
+
if not self.drop_last and len(balanced_indices) % self.num_sp_groups != 0:
|
| 675 |
+
sp_group_size += 1
|
| 676 |
+
|
| 677 |
+
num_batches = sp_group_size // self.batch_size
|
| 678 |
+
if not self.drop_last and sp_group_size % self.batch_size != 0:
|
| 679 |
+
num_batches += 1
|
| 680 |
+
total_batches += num_batches
|
| 681 |
+
return total_batches
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def collate_fn(batch):
|
| 685 |
+
batch = [item for item in batch if item is not None]
|
| 686 |
+
|
| 687 |
+
if len(batch) == 0:
|
| 688 |
+
return None
|
| 689 |
+
|
| 690 |
+
def collate_dict(data_list):
|
| 691 |
+
if isinstance(data_list[0], dict):
|
| 692 |
+
return {key: collate_dict([d[key] for d in data_list]) for key in data_list[0]}
|
| 693 |
+
elif isinstance(data_list[0], torch.Tensor):
|
| 694 |
+
return torch.stack(data_list)
|
| 695 |
+
else:
|
| 696 |
+
return data_list
|
| 697 |
+
|
| 698 |
+
return {key: collate_dict([d[key] for d in batch]) for key in batch[0]}
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
if __name__ == "__main__":
|
| 702 |
+
import torch.distributed.checkpoint as dcp
|
| 703 |
+
from accelerate import Accelerator
|
| 704 |
+
from torchdata.stateful_dataloader import StatefulDataLoader
|
| 705 |
+
|
| 706 |
+
json_file = [
|
| 707 |
+
"opensoraplan/jsons/video_mixkit_513f_1997.json",
|
| 708 |
+
]
|
| 709 |
+
video_folder = [
|
| 710 |
+
"opensoraplan/videos",
|
| 711 |
+
]
|
| 712 |
+
stride = 1
|
| 713 |
+
batch_size = 2
|
| 714 |
+
num_train_epochs = 1
|
| 715 |
+
seed = 0
|
| 716 |
+
num_workers = 8
|
| 717 |
+
output_dir = "accelerate_checkpoints"
|
| 718 |
+
checkpoint_dirs = (
|
| 719 |
+
[
|
| 720 |
+
d
|
| 721 |
+
for d in os.listdir(output_dir)
|
| 722 |
+
if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d))
|
| 723 |
+
]
|
| 724 |
+
if os.path.exists(output_dir)
|
| 725 |
+
else []
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
dataset_ratios = {}
|
| 729 |
+
# dataset_ratios = {
|
| 730 |
+
# "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v4/latents": 0.9,
|
| 731 |
+
# "/mnt/hdfs/data/ysh_new/userful_things_wan/sekai/sekai-real-walking-hq-193/latents_stride1": 0.1
|
| 732 |
+
# }
|
| 733 |
+
|
| 734 |
+
accelerator = Accelerator()
|
| 735 |
+
print(accelerator.process_index, accelerator.num_processes)
|
| 736 |
+
|
| 737 |
+
dataset = BucketedFeatureDataset(
|
| 738 |
+
json_files=json_file,
|
| 739 |
+
video_folders=video_folder,
|
| 740 |
+
stride=stride,
|
| 741 |
+
force_rebuild=False,
|
| 742 |
+
resolution=640,
|
| 743 |
+
single_res=True,
|
| 744 |
+
single_height=384,
|
| 745 |
+
single_width=640,
|
| 746 |
+
single_length=True,
|
| 747 |
+
single_num_frame=81,
|
| 748 |
+
multi_res=True,
|
| 749 |
+
)
|
| 750 |
+
sampler = BucketedSampler(
|
| 751 |
+
dataset,
|
| 752 |
+
batch_size=batch_size,
|
| 753 |
+
drop_last=True,
|
| 754 |
+
shuffle=False,
|
| 755 |
+
dataset_sampling_ratios=dataset_ratios,
|
| 756 |
+
seed=seed,
|
| 757 |
+
# num_sp_groups=get_world_size() // get_sp_world_size(),
|
| 758 |
+
# sp_world_size=get_sp_world_size(),
|
| 759 |
+
# global_rank=get_world_rank(),
|
| 760 |
+
num_sp_groups=accelerator.num_processes // 1,
|
| 761 |
+
sp_world_size=1,
|
| 762 |
+
global_rank=accelerator.process_index,
|
| 763 |
+
)
|
| 764 |
+
dataloader = StatefulDataLoader(dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=num_workers)
|
| 765 |
+
|
| 766 |
+
print(len(dataset), len(dataloader))
|
| 767 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 768 |
+
|
| 769 |
+
step = 0
|
| 770 |
+
global_step = 0
|
| 771 |
+
first_epoch = 0
|
| 772 |
+
num_update_steps_per_epoch = len(dataloader)
|
| 773 |
+
if checkpoint_dirs:
|
| 774 |
+
latest_checkpoint = max(checkpoint_dirs, key=lambda x: int(x.split("-")[1]))
|
| 775 |
+
checkpoint_path = os.path.join(output_dir, latest_checkpoint)
|
| 776 |
+
print(f"Found checkpoint: {checkpoint_path}")
|
| 777 |
+
|
| 778 |
+
accelerator.load_state(checkpoint_path)
|
| 779 |
+
global_step = int(latest_checkpoint.split("-")[1])
|
| 780 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 781 |
+
|
| 782 |
+
states = {
|
| 783 |
+
"dataloader": dataloader,
|
| 784 |
+
}
|
| 785 |
+
dcp_dir = os.path.join(checkpoint_path, "distributed_checkpoint")
|
| 786 |
+
dcp.load(states, checkpoint_id=dcp_dir)
|
| 787 |
+
|
| 788 |
+
print(f"Resuming from step {global_step}, epoch {first_epoch}")
|
| 789 |
+
|
| 790 |
+
print("Testing dataloader...")
|
| 791 |
+
step = global_step
|
| 792 |
+
dataset_counts = defaultdict(int)
|
| 793 |
+
for epoch in range(first_epoch, num_train_epochs):
|
| 794 |
+
sampler.set_epoch(epoch)
|
| 795 |
+
dataset.set_epoch(epoch)
|
| 796 |
+
for i, batch in enumerate(dataloader):
|
| 797 |
+
# Get metadata
|
| 798 |
+
uttid = batch["uttid"]
|
| 799 |
+
bucket_key = batch["bucket_key"]
|
| 800 |
+
num_frame = batch["video_metadata"]["num_frames"]
|
| 801 |
+
height = batch["video_metadata"]["height"]
|
| 802 |
+
width = batch["video_metadata"]["width"]
|
| 803 |
+
|
| 804 |
+
# Get feature
|
| 805 |
+
video_data = batch["videos"]
|
| 806 |
+
prompt = batch["prompts"]
|
| 807 |
+
first_frames_images = batch["first_frames_images"]
|
| 808 |
+
first_frames_images = [torchvision.transforms.ToPILImage()(x.to(torch.uint8)) for x in first_frames_images]
|
| 809 |
+
|
| 810 |
+
# save_frames(video_data[0].squeeze(0), video_path="1.mp4")
|
| 811 |
+
# import pdb;pdb.set_trace()
|
| 812 |
+
|
| 813 |
+
if accelerator.process_index == 0:
|
| 814 |
+
# print info
|
| 815 |
+
print(f" Step {step}:")
|
| 816 |
+
print(f" Batch {i}:")
|
| 817 |
+
# print(f" Data Name: {batch['dataset_name']}")
|
| 818 |
+
print(f" Batch size: {len(uttid)}")
|
| 819 |
+
print(f" Uttids: {uttid}")
|
| 820 |
+
print(f" Dimensions - frames: {num_frame[0]}, height: {height[0]}, width: {width[0]}")
|
| 821 |
+
print(f" Bucket key: {bucket_key[0]}")
|
| 822 |
+
print(f" Videos shape: {video_data.shape}")
|
| 823 |
+
print(f" Cpation: {prompt}")
|
| 824 |
+
|
| 825 |
+
# verify
|
| 826 |
+
assert all(nf == num_frame[0] for nf in num_frame), "Frame numbers not consistent in batch"
|
| 827 |
+
assert all(h == height[0] for h in height), "Heights not consistent in batch"
|
| 828 |
+
assert all(w == width[0] for w in width), "Widths not consistent in batch"
|
| 829 |
+
|
| 830 |
+
print(" ✓ Batch dimensions are consistent")
|
| 831 |
+
|
| 832 |
+
for dataset_name in batch["dataset_name"]:
|
| 833 |
+
dataset_counts[dataset_name] += 1
|
| 834 |
+
|
| 835 |
+
step += 1
|
| 836 |
+
|
| 837 |
+
# if step == 20:
|
| 838 |
+
# checkpoint_dir = f"checkpoint-{step}"
|
| 839 |
+
# save_path = os.path.join(output_dir, checkpoint_dir)
|
| 840 |
+
# os.makedirs(save_path, exist_ok=True)
|
| 841 |
+
|
| 842 |
+
# if accelerator.is_main_process:
|
| 843 |
+
# print(f"Saving checkpoint at step {step}")
|
| 844 |
+
|
| 845 |
+
# accelerator.save_state(save_path)
|
| 846 |
+
|
| 847 |
+
# print(accelerator.process_index, accelerator.num_processes)
|
| 848 |
+
# states = {
|
| 849 |
+
# "dataloader": dataloader,
|
| 850 |
+
# }
|
| 851 |
+
# dcp_dir = os.path.join(save_path, "distributed_checkpoint")
|
| 852 |
+
# dcp.save(states, checkpoint_id=dcp_dir)
|
| 853 |
+
|
| 854 |
+
print("实际采样统计:", dict(dataset_counts))
|
Helios/_DEV/helios/diffusers_version/__init__.py
ADDED
|
File without changes
|
Helios/_DEV/helios/diffusers_version/pipeline_helios_diffusers.py
ADDED
|
@@ -0,0 +1,1406 @@
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import html
|
| 16 |
+
import math
|
| 17 |
+
from itertools import accumulate
|
| 18 |
+
from typing import Any, Callable
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import regex as re
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 25 |
+
|
| 26 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 27 |
+
from diffusers.image_processor import PipelineImageInput
|
| 28 |
+
from diffusers.loaders import HeliosLoraLoaderMixin
|
| 29 |
+
from diffusers.models import AutoencoderKLWan, HeliosTransformer3DModel
|
| 30 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 31 |
+
from diffusers.schedulers import HeliosScheduler
|
| 32 |
+
from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
|
| 33 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 34 |
+
from diffusers.video_processor import VideoProcessor
|
| 35 |
+
|
| 36 |
+
from ..pipelines.pipeline_output import HeliosPipelineOutput
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if is_torch_xla_available():
|
| 40 |
+
import torch_xla.core.xla_model as xm
|
| 41 |
+
|
| 42 |
+
XLA_AVAILABLE = True
|
| 43 |
+
else:
|
| 44 |
+
XLA_AVAILABLE = False
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 47 |
+
|
| 48 |
+
if is_ftfy_available():
|
| 49 |
+
import ftfy
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
EXAMPLE_DOC_STRING = """
|
| 53 |
+
Examples:
|
| 54 |
+
```python
|
| 55 |
+
>>> import torch
|
| 56 |
+
>>> from diffusers.utils import export_to_video
|
| 57 |
+
>>> from diffusers import AutoencoderKLWan, HeliosPipeline
|
| 58 |
+
|
| 59 |
+
>>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled
|
| 60 |
+
>>> model_id = "BestWishYsh/Helios-Base"
|
| 61 |
+
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 62 |
+
>>> pipe = HeliosPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
|
| 63 |
+
>>> pipe.to("cuda")
|
| 64 |
+
|
| 65 |
+
>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
|
| 66 |
+
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
| 67 |
+
|
| 68 |
+
>>> output = pipe(
|
| 69 |
+
... prompt=prompt,
|
| 70 |
+
... negative_prompt=negative_prompt,
|
| 71 |
+
... height=384,
|
| 72 |
+
... width=640,
|
| 73 |
+
... num_frames=132,
|
| 74 |
+
... guidance_scale=5.0,
|
| 75 |
+
... ).frames[0]
|
| 76 |
+
>>> export_to_video(output, "output.mp4", fps=24)
|
| 77 |
+
```
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def optimized_scale(positive_flat, negative_flat):
|
| 82 |
+
positive_flat = positive_flat.float()
|
| 83 |
+
negative_flat = negative_flat.float()
|
| 84 |
+
# Calculate dot production
|
| 85 |
+
dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)
|
| 86 |
+
# Squared norm of uncondition
|
| 87 |
+
squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
|
| 88 |
+
# st_star = v_cond^T * v_uncond / ||v_uncond||^2
|
| 89 |
+
st_star = dot_product / squared_norm
|
| 90 |
+
return st_star
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def basic_clean(text):
|
| 94 |
+
text = ftfy.fix_text(text)
|
| 95 |
+
text = html.unescape(html.unescape(text))
|
| 96 |
+
return text.strip()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def whitespace_clean(text):
|
| 100 |
+
text = re.sub(r"\s+", " ", text)
|
| 101 |
+
text = text.strip()
|
| 102 |
+
return text
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def prompt_clean(text):
|
| 106 |
+
text = whitespace_clean(basic_clean(text))
|
| 107 |
+
return text
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
|
| 111 |
+
def calculate_shift(
|
| 112 |
+
image_seq_len,
|
| 113 |
+
base_seq_len: int = 256,
|
| 114 |
+
max_seq_len: int = 4096,
|
| 115 |
+
base_shift: float = 0.5,
|
| 116 |
+
max_shift: float = 1.15,
|
| 117 |
+
):
|
| 118 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
| 119 |
+
b = base_shift - m * base_seq_len
|
| 120 |
+
mu = image_seq_len * m + b
|
| 121 |
+
return mu
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class HeliosPipeline(DiffusionPipeline, HeliosLoraLoaderMixin):
|
| 125 |
+
r"""
|
| 126 |
+
Pipeline for text-to-video / image-to-video / video-to-video generation using Helios.
|
| 127 |
+
|
| 128 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 129 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
tokenizer ([`T5Tokenizer`]):
|
| 133 |
+
Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
|
| 134 |
+
specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 135 |
+
text_encoder ([`T5EncoderModel`]):
|
| 136 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
| 137 |
+
the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 138 |
+
transformer ([`HeliosTransformer3DModel`]):
|
| 139 |
+
Conditional Transformer to denoise the input latents.
|
| 140 |
+
scheduler ([`HeliosScheduler`]):
|
| 141 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 142 |
+
vae ([`AutoencoderKLWan`]):
|
| 143 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
| 147 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 148 |
+
_optional_components = ["transformer"]
|
| 149 |
+
|
| 150 |
+
def __init__(
|
| 151 |
+
self,
|
| 152 |
+
tokenizer: AutoTokenizer,
|
| 153 |
+
text_encoder: UMT5EncoderModel,
|
| 154 |
+
vae: AutoencoderKLWan,
|
| 155 |
+
scheduler: HeliosScheduler,
|
| 156 |
+
transformer: HeliosTransformer3DModel,
|
| 157 |
+
is_cfg_zero_star: bool = False,
|
| 158 |
+
is_distilled: bool = False,
|
| 159 |
+
):
|
| 160 |
+
super().__init__()
|
| 161 |
+
|
| 162 |
+
self.register_modules(
|
| 163 |
+
vae=vae,
|
| 164 |
+
text_encoder=text_encoder,
|
| 165 |
+
tokenizer=tokenizer,
|
| 166 |
+
transformer=transformer,
|
| 167 |
+
scheduler=scheduler,
|
| 168 |
+
)
|
| 169 |
+
self.register_to_config(is_cfg_zero_star=is_cfg_zero_star)
|
| 170 |
+
self.register_to_config(is_distilled=is_distilled)
|
| 171 |
+
self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
|
| 172 |
+
self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
|
| 173 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
| 174 |
+
|
| 175 |
+
def _get_t5_prompt_embeds(
|
| 176 |
+
self,
|
| 177 |
+
prompt: str | list[str] = None,
|
| 178 |
+
num_videos_per_prompt: int = 1,
|
| 179 |
+
max_sequence_length: int = 226,
|
| 180 |
+
device: torch.device | None = None,
|
| 181 |
+
dtype: torch.dtype | None = None,
|
| 182 |
+
):
|
| 183 |
+
device = device or self._execution_device
|
| 184 |
+
dtype = dtype or self.text_encoder.dtype
|
| 185 |
+
|
| 186 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 187 |
+
prompt = [prompt_clean(u) for u in prompt]
|
| 188 |
+
batch_size = len(prompt)
|
| 189 |
+
|
| 190 |
+
text_inputs = self.tokenizer(
|
| 191 |
+
prompt,
|
| 192 |
+
padding="max_length",
|
| 193 |
+
max_length=max_sequence_length,
|
| 194 |
+
truncation=True,
|
| 195 |
+
add_special_tokens=True,
|
| 196 |
+
return_attention_mask=True,
|
| 197 |
+
return_tensors="pt",
|
| 198 |
+
)
|
| 199 |
+
text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
| 200 |
+
seq_lens = mask.gt(0).sum(dim=1).long()
|
| 201 |
+
|
| 202 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
|
| 203 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 204 |
+
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
| 205 |
+
prompt_embeds = torch.stack(
|
| 206 |
+
[torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 210 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 211 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
| 212 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
| 213 |
+
|
| 214 |
+
return prompt_embeds, text_inputs.attention_mask.bool()
|
| 215 |
+
|
| 216 |
+
def encode_prompt(
|
| 217 |
+
self,
|
| 218 |
+
prompt: str | list[str],
|
| 219 |
+
negative_prompt: str | list[str] | None = None,
|
| 220 |
+
do_classifier_free_guidance: bool = True,
|
| 221 |
+
num_videos_per_prompt: int = 1,
|
| 222 |
+
prompt_embeds: torch.Tensor | None = None,
|
| 223 |
+
negative_prompt_embeds: torch.Tensor | None = None,
|
| 224 |
+
max_sequence_length: int = 226,
|
| 225 |
+
device: torch.device | None = None,
|
| 226 |
+
dtype: torch.dtype | None = None,
|
| 227 |
+
):
|
| 228 |
+
r"""
|
| 229 |
+
Encodes the prompt into text encoder hidden states.
|
| 230 |
+
|
| 231 |
+
Args:
|
| 232 |
+
prompt (`str` or `list[str]`, *optional*):
|
| 233 |
+
prompt to be encoded
|
| 234 |
+
negative_prompt (`str` or `list[str]`, *optional*):
|
| 235 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 236 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 237 |
+
less than `1`).
|
| 238 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 239 |
+
Whether to use classifier free guidance or not.
|
| 240 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 241 |
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
| 242 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 243 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 244 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 245 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 246 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 247 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 248 |
+
argument.
|
| 249 |
+
device: (`torch.device`, *optional*):
|
| 250 |
+
torch device
|
| 251 |
+
dtype: (`torch.dtype`, *optional*):
|
| 252 |
+
torch dtype
|
| 253 |
+
"""
|
| 254 |
+
device = device or self._execution_device
|
| 255 |
+
|
| 256 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 257 |
+
if prompt is not None:
|
| 258 |
+
batch_size = len(prompt)
|
| 259 |
+
else:
|
| 260 |
+
batch_size = prompt_embeds.shape[0]
|
| 261 |
+
|
| 262 |
+
if prompt_embeds is None:
|
| 263 |
+
prompt_embeds, _ = self._get_t5_prompt_embeds(
|
| 264 |
+
prompt=prompt,
|
| 265 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 266 |
+
max_sequence_length=max_sequence_length,
|
| 267 |
+
device=device,
|
| 268 |
+
dtype=dtype,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 272 |
+
negative_prompt = negative_prompt or ""
|
| 273 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
| 274 |
+
|
| 275 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 276 |
+
raise TypeError(
|
| 277 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 278 |
+
f" {type(prompt)}."
|
| 279 |
+
)
|
| 280 |
+
elif batch_size != len(negative_prompt):
|
| 281 |
+
raise ValueError(
|
| 282 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 283 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 284 |
+
" the batch size of `prompt`."
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
negative_prompt_embeds, _ = self._get_t5_prompt_embeds(
|
| 288 |
+
prompt=negative_prompt,
|
| 289 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 290 |
+
max_sequence_length=max_sequence_length,
|
| 291 |
+
device=device,
|
| 292 |
+
dtype=dtype,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
return prompt_embeds, negative_prompt_embeds
|
| 296 |
+
|
| 297 |
+
def check_inputs(
|
| 298 |
+
self,
|
| 299 |
+
prompt,
|
| 300 |
+
negative_prompt,
|
| 301 |
+
height,
|
| 302 |
+
width,
|
| 303 |
+
prompt_embeds=None,
|
| 304 |
+
negative_prompt_embeds=None,
|
| 305 |
+
callback_on_step_end_tensor_inputs=None,
|
| 306 |
+
image=None,
|
| 307 |
+
video=None,
|
| 308 |
+
use_interpolate_prompt=False,
|
| 309 |
+
num_videos_per_prompt=None,
|
| 310 |
+
interpolate_time_list=None,
|
| 311 |
+
interpolation_steps=None,
|
| 312 |
+
guidance_scale=None,
|
| 313 |
+
):
|
| 314 |
+
if height % 16 != 0 or width % 16 != 0:
|
| 315 |
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
| 316 |
+
|
| 317 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 318 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 319 |
+
):
|
| 320 |
+
raise ValueError(
|
| 321 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
if prompt is not None and prompt_embeds is not None:
|
| 325 |
+
raise ValueError(
|
| 326 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 327 |
+
" only forward one of the two."
|
| 328 |
+
)
|
| 329 |
+
elif negative_prompt is not None and negative_prompt_embeds is not None:
|
| 330 |
+
raise ValueError(
|
| 331 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
|
| 332 |
+
" only forward one of the two."
|
| 333 |
+
)
|
| 334 |
+
elif prompt is None and prompt_embeds is None:
|
| 335 |
+
raise ValueError(
|
| 336 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 337 |
+
)
|
| 338 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 339 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 340 |
+
elif negative_prompt is not None and (
|
| 341 |
+
not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
|
| 342 |
+
):
|
| 343 |
+
raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
|
| 344 |
+
|
| 345 |
+
if image is not None and video is not None:
|
| 346 |
+
raise ValueError("image and video cannot be provided simultaneously")
|
| 347 |
+
|
| 348 |
+
if use_interpolate_prompt:
|
| 349 |
+
assert num_videos_per_prompt == 1, f"num_videos_per_prompt must be 1, got {num_videos_per_prompt}"
|
| 350 |
+
assert isinstance(prompt, list), "prompt must be a list"
|
| 351 |
+
assert len(prompt) == len(interpolate_time_list), (
|
| 352 |
+
f"Length mismatch: {len(prompt)} vs {len(interpolate_time_list)}"
|
| 353 |
+
)
|
| 354 |
+
assert min(interpolate_time_list) > interpolation_steps, (
|
| 355 |
+
f"Minimum value {min(interpolate_time_list)} must be greater than {interpolation_steps}"
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
if guidance_scale > 1.0 and self.config.is_distilled:
|
| 359 |
+
logger.warning(f"Guidance scale {guidance_scale} is ignored for step-wise distilled models.")
|
| 360 |
+
|
| 361 |
+
def prepare_latents(
|
| 362 |
+
self,
|
| 363 |
+
batch_size: int,
|
| 364 |
+
num_channels_latents: int = 16,
|
| 365 |
+
height: int = 384,
|
| 366 |
+
width: int = 640,
|
| 367 |
+
num_frames: int = 33,
|
| 368 |
+
dtype: torch.dtype | None = None,
|
| 369 |
+
device: torch.device | None = None,
|
| 370 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 371 |
+
latents: torch.Tensor | None = None,
|
| 372 |
+
) -> torch.Tensor:
|
| 373 |
+
if latents is not None:
|
| 374 |
+
return latents.to(device=device, dtype=dtype)
|
| 375 |
+
|
| 376 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
| 377 |
+
shape = (
|
| 378 |
+
batch_size,
|
| 379 |
+
num_channels_latents,
|
| 380 |
+
num_latent_frames,
|
| 381 |
+
int(height) // self.vae_scale_factor_spatial,
|
| 382 |
+
int(width) // self.vae_scale_factor_spatial,
|
| 383 |
+
)
|
| 384 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 385 |
+
raise ValueError(
|
| 386 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 387 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 391 |
+
return latents
|
| 392 |
+
|
| 393 |
+
def prepare_image_latents(
|
| 394 |
+
self,
|
| 395 |
+
image: torch.Tensor,
|
| 396 |
+
latents_mean: torch.Tensor,
|
| 397 |
+
latents_std: torch.Tensor,
|
| 398 |
+
num_latent_frames_per_chunk: int,
|
| 399 |
+
dtype: torch.dtype | None = None,
|
| 400 |
+
device: torch.device | None = None,
|
| 401 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 402 |
+
latents: torch.Tensor | None = None,
|
| 403 |
+
fake_latents: torch.Tensor | None = None,
|
| 404 |
+
) -> torch.Tensor:
|
| 405 |
+
device = device or self._execution_device
|
| 406 |
+
if latents is None:
|
| 407 |
+
image = image.unsqueeze(2).to(device=device, dtype=self.vae.dtype)
|
| 408 |
+
latents = self.vae.encode(image).latent_dist.sample(generator=generator)
|
| 409 |
+
latents = (latents - latents_mean) * latents_std
|
| 410 |
+
if fake_latents is None:
|
| 411 |
+
min_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
|
| 412 |
+
fake_video = image.repeat(1, 1, min_frames, 1, 1).to(device=device, dtype=self.vae.dtype)
|
| 413 |
+
fake_latents_full = self.vae.encode(fake_video).latent_dist.sample(generator=generator)
|
| 414 |
+
fake_latents_full = (fake_latents_full - latents_mean) * latents_std
|
| 415 |
+
fake_latents = fake_latents_full[:, :, -1:, :, :]
|
| 416 |
+
return latents.to(device=device, dtype=dtype), fake_latents.to(device=device, dtype=dtype)
|
| 417 |
+
|
| 418 |
+
def prepare_video_latents(
|
| 419 |
+
self,
|
| 420 |
+
video: torch.Tensor,
|
| 421 |
+
latents_mean: torch.Tensor,
|
| 422 |
+
latents_std: torch.Tensor,
|
| 423 |
+
num_latent_frames_per_chunk: int,
|
| 424 |
+
dtype: torch.dtype | None = None,
|
| 425 |
+
device: torch.device | None = None,
|
| 426 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 427 |
+
latents: torch.Tensor | None = None,
|
| 428 |
+
) -> torch.Tensor:
|
| 429 |
+
device = device or self._execution_device
|
| 430 |
+
video = video.to(device=device, dtype=self.vae.dtype)
|
| 431 |
+
if latents is None:
|
| 432 |
+
num_frames = video.shape[2]
|
| 433 |
+
min_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
|
| 434 |
+
num_chunks = num_frames // min_frames
|
| 435 |
+
if num_chunks == 0:
|
| 436 |
+
raise ValueError(
|
| 437 |
+
f"Video must have at least {min_frames} frames "
|
| 438 |
+
f"(got {num_frames} frames). "
|
| 439 |
+
f"Required: (num_latent_frames_per_chunk - 1) * {self.vae_scale_factor_temporal} + 1 = ({num_latent_frames_per_chunk} - 1) * {self.vae_scale_factor_temporal} + 1 = {min_frames}"
|
| 440 |
+
)
|
| 441 |
+
total_valid_frames = num_chunks * min_frames
|
| 442 |
+
start_frame = num_frames - total_valid_frames
|
| 443 |
+
|
| 444 |
+
first_frame = video[:, :, 0:1, :, :]
|
| 445 |
+
first_frame_latent = self.vae.encode(first_frame).latent_dist.sample(generator=generator)
|
| 446 |
+
first_frame_latent = (first_frame_latent - latents_mean) * latents_std
|
| 447 |
+
|
| 448 |
+
latents_chunks = []
|
| 449 |
+
for i in range(num_chunks):
|
| 450 |
+
chunk_start = start_frame + i * min_frames
|
| 451 |
+
chunk_end = chunk_start + min_frames
|
| 452 |
+
video_chunk = video[:, :, chunk_start:chunk_end, :, :]
|
| 453 |
+
chunk_latents = self.vae.encode(video_chunk).latent_dist.sample(generator=generator)
|
| 454 |
+
chunk_latents = (chunk_latents - latents_mean) * latents_std
|
| 455 |
+
latents_chunks.append(chunk_latents)
|
| 456 |
+
latents = torch.cat(latents_chunks, dim=2)
|
| 457 |
+
return first_frame_latent.to(device=device, dtype=dtype), latents.to(device=device, dtype=dtype)
|
| 458 |
+
|
| 459 |
+
def interpolate_prompt_embeds(
|
| 460 |
+
self,
|
| 461 |
+
prompt_embeds_1: torch.Tensor,
|
| 462 |
+
prompt_embeds_2: torch.Tensor,
|
| 463 |
+
interpolation_steps: int = 3,
|
| 464 |
+
):
|
| 465 |
+
x = torch.lerp(
|
| 466 |
+
prompt_embeds_1,
|
| 467 |
+
prompt_embeds_2,
|
| 468 |
+
torch.linspace(0, 1, steps=interpolation_steps).unsqueeze(1).unsqueeze(2).to(prompt_embeds_1),
|
| 469 |
+
)
|
| 470 |
+
interpolated_prompt_embeds = list(x.chunk(interpolation_steps, dim=0))
|
| 471 |
+
return interpolated_prompt_embeds
|
| 472 |
+
|
| 473 |
+
def sample_block_noise(
|
| 474 |
+
self,
|
| 475 |
+
batch_size,
|
| 476 |
+
channel,
|
| 477 |
+
num_frames,
|
| 478 |
+
height,
|
| 479 |
+
width,
|
| 480 |
+
patch_size: tuple[int, ...] = (1, 2, 2),
|
| 481 |
+
device: torch.device | None = None,
|
| 482 |
+
generator: torch.Generator | None = None,
|
| 483 |
+
):
|
| 484 |
+
# NOTE: A generator must be provided to ensure correct and reproducible results.
|
| 485 |
+
# Creating a default generator here is a fallback only — without a fixed seed,
|
| 486 |
+
# the output will be non-deterministic and may produce incorrect results in CP context.
|
| 487 |
+
if generator is None:
|
| 488 |
+
generator = torch.Generator(device=device)
|
| 489 |
+
elif isinstance(generator, list):
|
| 490 |
+
generator = generator[0]
|
| 491 |
+
|
| 492 |
+
gamma = self.scheduler.config.gamma
|
| 493 |
+
_, ph, pw = patch_size
|
| 494 |
+
block_size = ph * pw
|
| 495 |
+
|
| 496 |
+
cov = (
|
| 497 |
+
torch.eye(block_size, device=device) * (1 + gamma)
|
| 498 |
+
- torch.ones(block_size, block_size, device=device) * gamma
|
| 499 |
+
)
|
| 500 |
+
cov += torch.eye(block_size, device=device) * 1e-8
|
| 501 |
+
cov = cov.float() # Upcast to fp32 for numerical stability — cholesky is unreliable in fp16/bf16.
|
| 502 |
+
|
| 503 |
+
L = torch.linalg.cholesky(cov)
|
| 504 |
+
block_number = batch_size * channel * num_frames * (height // ph) * (width // pw)
|
| 505 |
+
z = torch.randn(block_number, block_size, generator=generator, device=generator.device).to(device=device)
|
| 506 |
+
noise = z @ L.T
|
| 507 |
+
|
| 508 |
+
noise = noise.view(batch_size, channel, num_frames, height // ph, width // pw, ph, pw)
|
| 509 |
+
noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(batch_size, channel, num_frames, height, width)
|
| 510 |
+
|
| 511 |
+
return noise
|
| 512 |
+
|
| 513 |
+
def record_relative_l1(
|
| 514 |
+
self,
|
| 515 |
+
records: list[dict[str, float | int]] | None,
|
| 516 |
+
chunk_index: int,
|
| 517 |
+
stage_index: int | None,
|
| 518 |
+
step_index: int,
|
| 519 |
+
timestep: torch.Tensor,
|
| 520 |
+
latents_t: torch.Tensor,
|
| 521 |
+
latents_t_minus_1: torch.Tensor,
|
| 522 |
+
):
|
| 523 |
+
if records is None:
|
| 524 |
+
return
|
| 525 |
+
|
| 526 |
+
latents_t = latents_t.detach().float()
|
| 527 |
+
latents_t_minus_1 = latents_t_minus_1.detach().float()
|
| 528 |
+
delta_abs = (latents_t_minus_1 - latents_t).abs()
|
| 529 |
+
latents_abs = latents_t.abs()
|
| 530 |
+
relative_l1 = (delta_abs / latents_abs.clamp_min(1e-8)).mean()
|
| 531 |
+
relative_l1_ratio = delta_abs.mean() / latents_abs.mean().clamp_min(1e-8)
|
| 532 |
+
timestep_value = timestep.detach().float().mean().item() if torch.is_tensor(timestep) else float(timestep)
|
| 533 |
+
|
| 534 |
+
records.append(
|
| 535 |
+
{
|
| 536 |
+
"chunk_index": int(chunk_index),
|
| 537 |
+
"stage_index": -1 if stage_index is None else int(stage_index),
|
| 538 |
+
"step_index": int(step_index),
|
| 539 |
+
"timestep": float(timestep_value),
|
| 540 |
+
"relative_l1": float(relative_l1.item()),
|
| 541 |
+
"relative_l1_ratio": float(relative_l1_ratio.item()),
|
| 542 |
+
}
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
def stage1_sample(
|
| 546 |
+
self,
|
| 547 |
+
latents: torch.Tensor = None,
|
| 548 |
+
prompt_embeds: torch.Tensor = None,
|
| 549 |
+
negative_prompt_embeds: torch.Tensor = None,
|
| 550 |
+
timesteps: torch.Tensor = None,
|
| 551 |
+
guidance_scale: float | None = 5.0,
|
| 552 |
+
indices_hidden_states: torch.Tensor = None,
|
| 553 |
+
indices_latents_history_short: torch.Tensor = None,
|
| 554 |
+
indices_latents_history_mid: torch.Tensor = None,
|
| 555 |
+
indices_latents_history_long: torch.Tensor = None,
|
| 556 |
+
latents_history_short: torch.Tensor = None,
|
| 557 |
+
latents_history_mid: torch.Tensor = None,
|
| 558 |
+
latents_history_long: torch.Tensor = None,
|
| 559 |
+
attention_kwargs: dict | None = None,
|
| 560 |
+
device: torch.device | None = None,
|
| 561 |
+
transformer_dtype: torch.dtype = None,
|
| 562 |
+
generator: torch.Generator | None = None,
|
| 563 |
+
num_warmup_steps: int | None = None,
|
| 564 |
+
# ------------ CFG Zero ------------
|
| 565 |
+
use_zero_init: bool | None = True,
|
| 566 |
+
zero_steps: int | None = 1,
|
| 567 |
+
# ------------ Callback ------------
|
| 568 |
+
callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None,
|
| 569 |
+
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
| 570 |
+
progress_bar=None,
|
| 571 |
+
chunk_index: int = 0,
|
| 572 |
+
relative_l1_records: list[dict[str, float | int]] | None = None,
|
| 573 |
+
):
|
| 574 |
+
batch_size = latents.shape[0]
|
| 575 |
+
|
| 576 |
+
for i, t in enumerate(timesteps):
|
| 577 |
+
if self.interrupt:
|
| 578 |
+
continue
|
| 579 |
+
|
| 580 |
+
self._current_timestep = t
|
| 581 |
+
timestep = t.expand(latents.shape[0])
|
| 582 |
+
|
| 583 |
+
latent_model_input = latents.to(transformer_dtype)
|
| 584 |
+
with self.transformer.cache_context("cond"):
|
| 585 |
+
noise_pred = self.transformer(
|
| 586 |
+
hidden_states=latent_model_input,
|
| 587 |
+
timestep=timestep,
|
| 588 |
+
encoder_hidden_states=prompt_embeds,
|
| 589 |
+
indices_hidden_states=indices_hidden_states,
|
| 590 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 591 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 592 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 593 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 594 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 595 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 596 |
+
attention_kwargs=attention_kwargs,
|
| 597 |
+
return_dict=False,
|
| 598 |
+
)[0]
|
| 599 |
+
|
| 600 |
+
if self.do_classifier_free_guidance:
|
| 601 |
+
with self.transformer.cache_context("uncond"):
|
| 602 |
+
noise_uncond = self.transformer(
|
| 603 |
+
hidden_states=latent_model_input,
|
| 604 |
+
timestep=timestep,
|
| 605 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 606 |
+
indices_hidden_states=indices_hidden_states,
|
| 607 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 608 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 609 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 610 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 611 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 612 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 613 |
+
attention_kwargs=attention_kwargs,
|
| 614 |
+
return_dict=False,
|
| 615 |
+
)[0]
|
| 616 |
+
|
| 617 |
+
if self.config.is_cfg_zero_star:
|
| 618 |
+
noise_pred_text = noise_pred
|
| 619 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 620 |
+
negative_flat = noise_uncond.view(batch_size, -1)
|
| 621 |
+
|
| 622 |
+
alpha = optimized_scale(positive_flat, negative_flat)
|
| 623 |
+
alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
|
| 624 |
+
alpha = alpha.to(noise_pred_text.dtype)
|
| 625 |
+
|
| 626 |
+
if (i <= zero_steps) and use_zero_init:
|
| 627 |
+
noise_pred = noise_pred_text * 0.0
|
| 628 |
+
else:
|
| 629 |
+
noise_pred = noise_uncond * alpha + guidance_scale * (noise_pred_text - noise_uncond * alpha)
|
| 630 |
+
else:
|
| 631 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
| 632 |
+
|
| 633 |
+
latents_t = latents
|
| 634 |
+
latents = self.scheduler.step(
|
| 635 |
+
noise_pred,
|
| 636 |
+
t,
|
| 637 |
+
latents,
|
| 638 |
+
return_dict=False,
|
| 639 |
+
)[0]
|
| 640 |
+
self.record_relative_l1(relative_l1_records, chunk_index, None, i, t, latents_t, latents)
|
| 641 |
+
|
| 642 |
+
if callback_on_step_end is not None:
|
| 643 |
+
callback_kwargs = {}
|
| 644 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 645 |
+
callback_kwargs[k] = locals()[k]
|
| 646 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 647 |
+
|
| 648 |
+
latents = callback_outputs.pop("latents", latents)
|
| 649 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 650 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 651 |
+
|
| 652 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 653 |
+
progress_bar.update()
|
| 654 |
+
|
| 655 |
+
if XLA_AVAILABLE:
|
| 656 |
+
xm.mark_step()
|
| 657 |
+
|
| 658 |
+
return latents
|
| 659 |
+
|
| 660 |
+
def stage2_sample(
|
| 661 |
+
self,
|
| 662 |
+
latents: torch.Tensor = None,
|
| 663 |
+
pyramid_num_stages: int = None,
|
| 664 |
+
pyramid_num_inference_steps_list: list[int] = None,
|
| 665 |
+
prompt_embeds: torch.Tensor = None,
|
| 666 |
+
negative_prompt_embeds: torch.Tensor = None,
|
| 667 |
+
guidance_scale: float | None = 5.0,
|
| 668 |
+
indices_hidden_states: torch.Tensor = None,
|
| 669 |
+
indices_latents_history_short: torch.Tensor = None,
|
| 670 |
+
indices_latents_history_mid: torch.Tensor = None,
|
| 671 |
+
indices_latents_history_long: torch.Tensor = None,
|
| 672 |
+
latents_history_short: torch.Tensor = None,
|
| 673 |
+
latents_history_mid: torch.Tensor = None,
|
| 674 |
+
latents_history_long: torch.Tensor = None,
|
| 675 |
+
attention_kwargs: dict | None = None,
|
| 676 |
+
device: torch.device | None = None,
|
| 677 |
+
transformer_dtype: torch.dtype = None,
|
| 678 |
+
generator: torch.Generator | None = None,
|
| 679 |
+
# ------------ CFG Zero ------------
|
| 680 |
+
use_zero_init: bool | None = True,
|
| 681 |
+
zero_steps: int | None = 1,
|
| 682 |
+
# -------------- DMD --------------
|
| 683 |
+
is_amplify_first_chunk: bool = False,
|
| 684 |
+
# ------------ Callback ------------
|
| 685 |
+
callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None,
|
| 686 |
+
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
| 687 |
+
progress_bar=None,
|
| 688 |
+
chunk_index: int = 0,
|
| 689 |
+
relative_l1_records: list[dict[str, float | int]] | None = None,
|
| 690 |
+
):
|
| 691 |
+
batch_size, num_channel, num_frames, height, width = latents.shape
|
| 692 |
+
latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, num_channel, height, width)
|
| 693 |
+
for _ in range(pyramid_num_stages - 1):
|
| 694 |
+
height //= 2
|
| 695 |
+
width //= 2
|
| 696 |
+
latents = (
|
| 697 |
+
F.interpolate(
|
| 698 |
+
latents,
|
| 699 |
+
size=(height, width),
|
| 700 |
+
mode="bilinear",
|
| 701 |
+
)
|
| 702 |
+
* 2
|
| 703 |
+
)
|
| 704 |
+
latents = latents.reshape(batch_size, num_frames, num_channel, height, width).permute(0, 2, 1, 3, 4)
|
| 705 |
+
|
| 706 |
+
batch_size = latents.shape[0]
|
| 707 |
+
start_point_list = None
|
| 708 |
+
if self.config.is_distilled:
|
| 709 |
+
start_point_list = [latents]
|
| 710 |
+
|
| 711 |
+
i = 0
|
| 712 |
+
for i_s in range(pyramid_num_stages):
|
| 713 |
+
patch_size = self.transformer.config.patch_size
|
| 714 |
+
image_seq_len = (latents.shape[-1] * latents.shape[-2] * latents.shape[-3]) // (
|
| 715 |
+
patch_size[0] * patch_size[1] * patch_size[2]
|
| 716 |
+
)
|
| 717 |
+
mu = calculate_shift(
|
| 718 |
+
image_seq_len,
|
| 719 |
+
self.scheduler.config.get("base_image_seq_len", 256),
|
| 720 |
+
self.scheduler.config.get("max_image_seq_len", 4096),
|
| 721 |
+
self.scheduler.config.get("base_shift", 0.5),
|
| 722 |
+
self.scheduler.config.get("max_shift", 1.15),
|
| 723 |
+
)
|
| 724 |
+
self.scheduler.set_timesteps(
|
| 725 |
+
pyramid_num_inference_steps_list[i_s],
|
| 726 |
+
i_s,
|
| 727 |
+
device=device,
|
| 728 |
+
mu=mu,
|
| 729 |
+
is_amplify_first_chunk=is_amplify_first_chunk,
|
| 730 |
+
)
|
| 731 |
+
timesteps = self.scheduler.timesteps
|
| 732 |
+
|
| 733 |
+
if i_s > 0:
|
| 734 |
+
height *= 2
|
| 735 |
+
width *= 2
|
| 736 |
+
num_frames = latents.shape[2]
|
| 737 |
+
latents = latents.permute(0, 2, 1, 3, 4).reshape(
|
| 738 |
+
batch_size * num_frames, num_channel, height // 2, width // 2
|
| 739 |
+
)
|
| 740 |
+
latents = F.interpolate(latents, size=(height, width), mode="nearest")
|
| 741 |
+
latents = latents.reshape(batch_size, num_frames, num_channel, height, width).permute(0, 2, 1, 3, 4)
|
| 742 |
+
# Fix the stage
|
| 743 |
+
ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal
|
| 744 |
+
gamma = self.scheduler.config.gamma
|
| 745 |
+
alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)
|
| 746 |
+
beta = alpha * (1 - ori_sigma) / math.sqrt(gamma)
|
| 747 |
+
|
| 748 |
+
batch_size, channel, num_frames, height, width = latents.shape
|
| 749 |
+
noise = self.sample_block_noise(
|
| 750 |
+
batch_size, channel, num_frames, height, width, patch_size, device, generator
|
| 751 |
+
)
|
| 752 |
+
noise = noise.to(device=device, dtype=transformer_dtype)
|
| 753 |
+
latents = alpha * latents + beta * noise # To fix the block artifact
|
| 754 |
+
|
| 755 |
+
if self.config.is_distilled:
|
| 756 |
+
start_point_list.append(latents)
|
| 757 |
+
|
| 758 |
+
for idx, t in enumerate(timesteps):
|
| 759 |
+
timestep = t.expand(latents.shape[0]).to(torch.int64)
|
| 760 |
+
|
| 761 |
+
with self.transformer.cache_context("cond"):
|
| 762 |
+
noise_pred = self.transformer(
|
| 763 |
+
hidden_states=latents.to(transformer_dtype),
|
| 764 |
+
timestep=timestep,
|
| 765 |
+
encoder_hidden_states=prompt_embeds,
|
| 766 |
+
attention_kwargs=attention_kwargs,
|
| 767 |
+
return_dict=False,
|
| 768 |
+
indices_hidden_states=indices_hidden_states,
|
| 769 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 770 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 771 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 772 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 773 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 774 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 775 |
+
)[0]
|
| 776 |
+
|
| 777 |
+
if self.do_classifier_free_guidance:
|
| 778 |
+
with self.transformer.cache_context("uncond"):
|
| 779 |
+
noise_uncond = self.transformer(
|
| 780 |
+
hidden_states=latents.to(transformer_dtype),
|
| 781 |
+
timestep=timestep,
|
| 782 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 783 |
+
attention_kwargs=attention_kwargs,
|
| 784 |
+
return_dict=False,
|
| 785 |
+
indices_hidden_states=indices_hidden_states,
|
| 786 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 787 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 788 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 789 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 790 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 791 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 792 |
+
)[0]
|
| 793 |
+
|
| 794 |
+
if self.config.is_cfg_zero_star:
|
| 795 |
+
noise_pred_text = noise_pred
|
| 796 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 797 |
+
negative_flat = noise_uncond.view(batch_size, -1)
|
| 798 |
+
|
| 799 |
+
alpha = optimized_scale(positive_flat, negative_flat)
|
| 800 |
+
alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
|
| 801 |
+
alpha = alpha.to(noise_pred_text.dtype)
|
| 802 |
+
|
| 803 |
+
if (i_s == 0 and idx <= zero_steps) and use_zero_init:
|
| 804 |
+
noise_pred = noise_pred_text * 0.0
|
| 805 |
+
else:
|
| 806 |
+
noise_pred = noise_uncond * alpha + guidance_scale * (
|
| 807 |
+
noise_pred_text - noise_uncond * alpha
|
| 808 |
+
)
|
| 809 |
+
else:
|
| 810 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
| 811 |
+
|
| 812 |
+
latents_t = latents
|
| 813 |
+
latents = self.scheduler.step(
|
| 814 |
+
noise_pred,
|
| 815 |
+
t,
|
| 816 |
+
latents,
|
| 817 |
+
generator=generator,
|
| 818 |
+
return_dict=False,
|
| 819 |
+
cur_sampling_step=idx,
|
| 820 |
+
dmd_noisy_tensor=start_point_list[i_s] if start_point_list is not None else None,
|
| 821 |
+
dmd_sigmas=self.scheduler.sigmas,
|
| 822 |
+
dmd_timesteps=self.scheduler.timesteps,
|
| 823 |
+
all_timesteps=timesteps,
|
| 824 |
+
)[0]
|
| 825 |
+
self.record_relative_l1(relative_l1_records, chunk_index, i_s, i, t, latents_t, latents)
|
| 826 |
+
|
| 827 |
+
if callback_on_step_end is not None:
|
| 828 |
+
callback_kwargs = {}
|
| 829 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 830 |
+
callback_kwargs[k] = locals()[k]
|
| 831 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 832 |
+
|
| 833 |
+
latents = callback_outputs.pop("latents", latents)
|
| 834 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 835 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 836 |
+
|
| 837 |
+
progress_bar.update()
|
| 838 |
+
|
| 839 |
+
if XLA_AVAILABLE:
|
| 840 |
+
xm.mark_step()
|
| 841 |
+
|
| 842 |
+
i += 1
|
| 843 |
+
|
| 844 |
+
return latents
|
| 845 |
+
|
| 846 |
+
@property
|
| 847 |
+
def guidance_scale(self):
|
| 848 |
+
return self._guidance_scale
|
| 849 |
+
|
| 850 |
+
@property
|
| 851 |
+
def do_classifier_free_guidance(self):
|
| 852 |
+
return self._guidance_scale > 1.0
|
| 853 |
+
|
| 854 |
+
@property
|
| 855 |
+
def num_timesteps(self):
|
| 856 |
+
return self._num_timesteps
|
| 857 |
+
|
| 858 |
+
@property
|
| 859 |
+
def current_timestep(self):
|
| 860 |
+
return self._current_timestep
|
| 861 |
+
|
| 862 |
+
@property
|
| 863 |
+
def interrupt(self):
|
| 864 |
+
return self._interrupt
|
| 865 |
+
|
| 866 |
+
@property
|
| 867 |
+
def attention_kwargs(self):
|
| 868 |
+
return self._attention_kwargs
|
| 869 |
+
|
| 870 |
+
@torch.no_grad()
|
| 871 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 872 |
+
def __call__(
|
| 873 |
+
self,
|
| 874 |
+
prompt: str | list[str] = None,
|
| 875 |
+
negative_prompt: str | list[str] = None,
|
| 876 |
+
height: int = 384,
|
| 877 |
+
width: int = 640,
|
| 878 |
+
num_frames: int = 132,
|
| 879 |
+
num_inference_steps: int = 50,
|
| 880 |
+
sigmas: list[float] = None,
|
| 881 |
+
guidance_scale: float = 5.0,
|
| 882 |
+
num_videos_per_prompt: int | None = 1,
|
| 883 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 884 |
+
latents: torch.Tensor | None = None,
|
| 885 |
+
prompt_embeds: torch.Tensor | None = None,
|
| 886 |
+
negative_prompt_embeds: torch.Tensor | None = None,
|
| 887 |
+
output_type: str | None = "np",
|
| 888 |
+
return_dict: bool = True,
|
| 889 |
+
attention_kwargs: dict[str, Any] | None = None,
|
| 890 |
+
callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None,
|
| 891 |
+
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
| 892 |
+
max_sequence_length: int = 512,
|
| 893 |
+
# ------------ I2V ------------
|
| 894 |
+
image: PipelineImageInput | None = None,
|
| 895 |
+
image_latents: torch.Tensor | None = None,
|
| 896 |
+
fake_image_latents: torch.Tensor | None = None,
|
| 897 |
+
add_noise_to_image_latents: bool = True,
|
| 898 |
+
image_noise_sigma_min: float = 0.111,
|
| 899 |
+
image_noise_sigma_max: float = 0.135,
|
| 900 |
+
# ------------ V2V ------------
|
| 901 |
+
video: PipelineImageInput | None = None,
|
| 902 |
+
video_latents: torch.Tensor | None = None,
|
| 903 |
+
add_noise_to_video_latents: bool = True,
|
| 904 |
+
video_noise_sigma_min: float = 0.111,
|
| 905 |
+
video_noise_sigma_max: float = 0.135,
|
| 906 |
+
# ------------ Interactive ------------
|
| 907 |
+
use_interpolate_prompt: bool = False,
|
| 908 |
+
interpolate_time_list: list = [7, 7, 7],
|
| 909 |
+
interpolation_steps: int = 3,
|
| 910 |
+
# ------------ Stage 1 ------------
|
| 911 |
+
history_sizes: list = [16, 2, 1],
|
| 912 |
+
num_latent_frames_per_chunk: int = 9,
|
| 913 |
+
keep_first_frame: bool = True,
|
| 914 |
+
is_skip_first_chunk: bool = False,
|
| 915 |
+
# ------------ Stage 2 ------------
|
| 916 |
+
is_enable_stage2: bool = False,
|
| 917 |
+
pyramid_num_stages: int = 3,
|
| 918 |
+
pyramid_num_inference_steps_list: list = [10, 10, 10],
|
| 919 |
+
# ------------ CFG Zero ------------
|
| 920 |
+
use_zero_init: bool | None = True,
|
| 921 |
+
zero_steps: int | None = 1,
|
| 922 |
+
# ------------ DMD ------------
|
| 923 |
+
is_amplify_first_chunk: bool = False,
|
| 924 |
+
# ------------ Debug ------------
|
| 925 |
+
output_relative_l1: bool = False,
|
| 926 |
+
):
|
| 927 |
+
r"""
|
| 928 |
+
The call function to the pipeline for generation.
|
| 929 |
+
|
| 930 |
+
Args:
|
| 931 |
+
prompt (`str` or `list[str]`, *optional*):
|
| 932 |
+
The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
|
| 933 |
+
negative_prompt (`str` or `list[str]`, *optional*):
|
| 934 |
+
The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
|
| 935 |
+
instead. Ignored when not using guidance (`guidance_scale` < `1`).
|
| 936 |
+
height (`int`, defaults to `384`):
|
| 937 |
+
The height in pixels of the generated image.
|
| 938 |
+
width (`int`, defaults to `640`):
|
| 939 |
+
The width in pixels of the generated image.
|
| 940 |
+
num_frames (`int`, defaults to `132`):
|
| 941 |
+
The number of frames in the generated video.
|
| 942 |
+
num_inference_steps (`int`, defaults to `50`):
|
| 943 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 944 |
+
expense of slower inference.
|
| 945 |
+
guidance_scale (`float`, defaults to `5.0`):
|
| 946 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
| 947 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
| 948 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
| 949 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
| 950 |
+
the text `prompt`, usually at the expense of lower image quality.
|
| 951 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 952 |
+
The number of images to generate per prompt.
|
| 953 |
+
generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
|
| 954 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 955 |
+
generation deterministic.
|
| 956 |
+
latents (`torch.Tensor`, *optional*):
|
| 957 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 958 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 959 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 960 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 961 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 962 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 963 |
+
output_type (`str`, *optional*, defaults to `"np"`):
|
| 964 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 965 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 966 |
+
Whether or not to return a [`HeliosPipelineOutput`] instead of a plain tuple.
|
| 967 |
+
attention_kwargs (`dict`, *optional*):
|
| 968 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 969 |
+
`self.processor` in
|
| 970 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 971 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
| 972 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
| 973 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
| 974 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
| 975 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
| 976 |
+
callback_on_step_end_tensor_inputs (`list`, *optional*):
|
| 977 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 978 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 979 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 980 |
+
max_sequence_length (`int`, defaults to `512`):
|
| 981 |
+
The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
|
| 982 |
+
truncated. If the prompt is shorter, it will be padded to this length.
|
| 983 |
+
|
| 984 |
+
Examples:
|
| 985 |
+
|
| 986 |
+
Returns:
|
| 987 |
+
[`~HeliosPipelineOutput`] or `tuple`:
|
| 988 |
+
If `return_dict` is `True`, [`HeliosPipelineOutput`] is returned, otherwise a `tuple` is returned where
|
| 989 |
+
the first element is a list with the generated images and the second element is a list of `bool`s
|
| 990 |
+
indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
|
| 991 |
+
"""
|
| 992 |
+
|
| 993 |
+
if image is not None and video is not None:
|
| 994 |
+
raise ValueError("image and video cannot be provided simultaneously")
|
| 995 |
+
|
| 996 |
+
history_sizes = sorted(history_sizes, reverse=True) # From big to small
|
| 997 |
+
|
| 998 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
| 999 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
| 1000 |
+
|
| 1001 |
+
# 1. Check inputs. Raise error if not correct
|
| 1002 |
+
self.check_inputs(
|
| 1003 |
+
prompt,
|
| 1004 |
+
negative_prompt,
|
| 1005 |
+
height,
|
| 1006 |
+
width,
|
| 1007 |
+
prompt_embeds,
|
| 1008 |
+
negative_prompt_embeds,
|
| 1009 |
+
callback_on_step_end_tensor_inputs,
|
| 1010 |
+
image,
|
| 1011 |
+
video,
|
| 1012 |
+
use_interpolate_prompt,
|
| 1013 |
+
num_videos_per_prompt,
|
| 1014 |
+
interpolate_time_list,
|
| 1015 |
+
interpolation_steps,
|
| 1016 |
+
guidance_scale,
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
num_frames = max(num_frames, 1)
|
| 1020 |
+
|
| 1021 |
+
self._guidance_scale = guidance_scale
|
| 1022 |
+
self._attention_kwargs = attention_kwargs
|
| 1023 |
+
self._current_timestep = None
|
| 1024 |
+
self._interrupt = False
|
| 1025 |
+
relative_l1_records = [] if output_relative_l1 else None
|
| 1026 |
+
|
| 1027 |
+
device = self._execution_device
|
| 1028 |
+
vae_dtype = self.vae.dtype
|
| 1029 |
+
|
| 1030 |
+
latents_mean = (
|
| 1031 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 1032 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 1033 |
+
.to(device, self.vae.dtype)
|
| 1034 |
+
)
|
| 1035 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
| 1036 |
+
device, self.vae.dtype
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
# 2. Define call parameters
|
| 1040 |
+
if use_interpolate_prompt or (prompt is not None and isinstance(prompt, str)):
|
| 1041 |
+
batch_size = 1
|
| 1042 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 1043 |
+
batch_size = len(prompt)
|
| 1044 |
+
else:
|
| 1045 |
+
batch_size = prompt_embeds.shape[0]
|
| 1046 |
+
|
| 1047 |
+
# 3. Encode input prompt
|
| 1048 |
+
if use_interpolate_prompt:
|
| 1049 |
+
interpolate_interval_idx = None
|
| 1050 |
+
interpolate_embeds = None
|
| 1051 |
+
interpolate_cumulative_list = list(accumulate(interpolate_time_list))
|
| 1052 |
+
|
| 1053 |
+
all_prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 1054 |
+
prompt=prompt,
|
| 1055 |
+
negative_prompt=negative_prompt,
|
| 1056 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 1057 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 1058 |
+
prompt_embeds=prompt_embeds,
|
| 1059 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1060 |
+
max_sequence_length=max_sequence_length,
|
| 1061 |
+
device=device,
|
| 1062 |
+
)
|
| 1063 |
+
|
| 1064 |
+
transformer_dtype = self.transformer.dtype
|
| 1065 |
+
all_prompt_embeds = all_prompt_embeds.to(transformer_dtype)
|
| 1066 |
+
if negative_prompt_embeds is not None:
|
| 1067 |
+
if use_interpolate_prompt:
|
| 1068 |
+
negative_prompt_embeds = negative_prompt_embeds[0].unsqueeze(0)
|
| 1069 |
+
negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
| 1070 |
+
|
| 1071 |
+
# 4. Prepare image or video
|
| 1072 |
+
if image is not None:
|
| 1073 |
+
image = self.video_processor.preprocess(image, height=height, width=width)
|
| 1074 |
+
image_latents, fake_image_latents = self.prepare_image_latents(
|
| 1075 |
+
image,
|
| 1076 |
+
latents_mean=latents_mean,
|
| 1077 |
+
latents_std=latents_std,
|
| 1078 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 1079 |
+
dtype=torch.float32,
|
| 1080 |
+
device=device,
|
| 1081 |
+
generator=generator,
|
| 1082 |
+
latents=image_latents,
|
| 1083 |
+
fake_latents=fake_image_latents,
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
if image_latents is not None and add_noise_to_image_latents:
|
| 1087 |
+
image_noise_sigma = (
|
| 1088 |
+
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
|
| 1089 |
+
+ image_noise_sigma_min
|
| 1090 |
+
)
|
| 1091 |
+
image_latents = (
|
| 1092 |
+
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1093 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1094 |
+
)
|
| 1095 |
+
fake_image_noise_sigma = (
|
| 1096 |
+
torch.rand(1, device=device, generator=generator) * (video_noise_sigma_max - video_noise_sigma_min)
|
| 1097 |
+
+ video_noise_sigma_min
|
| 1098 |
+
)
|
| 1099 |
+
fake_image_latents = (
|
| 1100 |
+
fake_image_noise_sigma * randn_tensor(fake_image_latents.shape, generator=generator, device=device)
|
| 1101 |
+
+ (1 - fake_image_noise_sigma) * fake_image_latents
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
if video is not None:
|
| 1105 |
+
video = self.video_processor.preprocess_video(video, height=height, width=width)
|
| 1106 |
+
image_latents, video_latents = self.prepare_video_latents(
|
| 1107 |
+
video,
|
| 1108 |
+
latents_mean=latents_mean,
|
| 1109 |
+
latents_std=latents_std,
|
| 1110 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 1111 |
+
dtype=torch.float32,
|
| 1112 |
+
device=device,
|
| 1113 |
+
generator=generator,
|
| 1114 |
+
latents=video_latents,
|
| 1115 |
+
)
|
| 1116 |
+
|
| 1117 |
+
if video_latents is not None and add_noise_to_video_latents:
|
| 1118 |
+
image_noise_sigma = (
|
| 1119 |
+
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
|
| 1120 |
+
+ image_noise_sigma_min
|
| 1121 |
+
)
|
| 1122 |
+
image_latents = (
|
| 1123 |
+
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1124 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1125 |
+
)
|
| 1126 |
+
|
| 1127 |
+
noisy_latents_chunks = []
|
| 1128 |
+
num_latent_chunks = video_latents.shape[2] // num_latent_frames_per_chunk
|
| 1129 |
+
for i in range(num_latent_chunks):
|
| 1130 |
+
chunk_start = i * num_latent_frames_per_chunk
|
| 1131 |
+
chunk_end = chunk_start + num_latent_frames_per_chunk
|
| 1132 |
+
latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :]
|
| 1133 |
+
|
| 1134 |
+
chunk_frames = latent_chunk.shape[2]
|
| 1135 |
+
frame_sigmas = (
|
| 1136 |
+
torch.rand(chunk_frames, device=device, generator=generator)
|
| 1137 |
+
* (video_noise_sigma_max - video_noise_sigma_min)
|
| 1138 |
+
+ video_noise_sigma_min
|
| 1139 |
+
)
|
| 1140 |
+
frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1)
|
| 1141 |
+
|
| 1142 |
+
noisy_chunk = (
|
| 1143 |
+
frame_sigmas * randn_tensor(latent_chunk.shape, generator=generator, device=device)
|
| 1144 |
+
+ (1 - frame_sigmas) * latent_chunk
|
| 1145 |
+
)
|
| 1146 |
+
noisy_latents_chunks.append(noisy_chunk)
|
| 1147 |
+
video_latents = torch.cat(noisy_latents_chunks, dim=2)
|
| 1148 |
+
|
| 1149 |
+
# 5. Prepare latent variables
|
| 1150 |
+
num_channels_latents = self.transformer.config.in_channels
|
| 1151 |
+
window_num_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
|
| 1152 |
+
num_latent_chunk = max(1, (num_frames + window_num_frames - 1) // window_num_frames)
|
| 1153 |
+
num_history_latent_frames = sum(history_sizes)
|
| 1154 |
+
history_video = None
|
| 1155 |
+
total_generated_latent_frames = 0
|
| 1156 |
+
|
| 1157 |
+
if not keep_first_frame:
|
| 1158 |
+
history_sizes[-1] = history_sizes[-1] + 1
|
| 1159 |
+
history_latents = torch.zeros(
|
| 1160 |
+
batch_size,
|
| 1161 |
+
num_channels_latents,
|
| 1162 |
+
num_history_latent_frames,
|
| 1163 |
+
height // self.vae_scale_factor_spatial,
|
| 1164 |
+
width // self.vae_scale_factor_spatial,
|
| 1165 |
+
device=device,
|
| 1166 |
+
dtype=torch.float32,
|
| 1167 |
+
)
|
| 1168 |
+
if fake_image_latents is not None:
|
| 1169 |
+
history_latents = torch.cat([history_latents[:, :, :-1, :, :], fake_image_latents], dim=2)
|
| 1170 |
+
total_generated_latent_frames += 1
|
| 1171 |
+
if video_latents is not None:
|
| 1172 |
+
history_frames = history_latents.shape[2]
|
| 1173 |
+
video_frames = video_latents.shape[2]
|
| 1174 |
+
if video_frames < history_frames:
|
| 1175 |
+
keep_frames = history_frames - video_frames
|
| 1176 |
+
history_latents = torch.cat([history_latents[:, :, :keep_frames, :, :], video_latents], dim=2)
|
| 1177 |
+
else:
|
| 1178 |
+
history_latents = video_latents
|
| 1179 |
+
total_generated_latent_frames += video_latents.shape[2]
|
| 1180 |
+
|
| 1181 |
+
if keep_first_frame:
|
| 1182 |
+
indices = torch.arange(0, sum([1, *history_sizes, num_latent_frames_per_chunk]))
|
| 1183 |
+
(
|
| 1184 |
+
indices_prefix,
|
| 1185 |
+
indices_latents_history_long,
|
| 1186 |
+
indices_latents_history_mid,
|
| 1187 |
+
indices_latents_history_1x,
|
| 1188 |
+
indices_hidden_states,
|
| 1189 |
+
) = indices.split([1, *history_sizes, num_latent_frames_per_chunk], dim=0)
|
| 1190 |
+
indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0)
|
| 1191 |
+
else:
|
| 1192 |
+
indices = torch.arange(0, sum([*history_sizes, num_latent_frames_per_chunk]))
|
| 1193 |
+
(
|
| 1194 |
+
indices_latents_history_long,
|
| 1195 |
+
indices_latents_history_mid,
|
| 1196 |
+
indices_latents_history_short,
|
| 1197 |
+
indices_hidden_states,
|
| 1198 |
+
) = indices.split([*history_sizes, num_latent_frames_per_chunk], dim=0)
|
| 1199 |
+
indices_hidden_states = indices_hidden_states.unsqueeze(0)
|
| 1200 |
+
indices_latents_history_short = indices_latents_history_short.unsqueeze(0)
|
| 1201 |
+
indices_latents_history_mid = indices_latents_history_mid.unsqueeze(0)
|
| 1202 |
+
indices_latents_history_long = indices_latents_history_long.unsqueeze(0)
|
| 1203 |
+
|
| 1204 |
+
# 6. Denoising loop
|
| 1205 |
+
if use_interpolate_prompt:
|
| 1206 |
+
if num_latent_chunk < max(interpolate_cumulative_list):
|
| 1207 |
+
num_latent_chunk = sum(interpolate_cumulative_list)
|
| 1208 |
+
print(f"Update num_latent_chunk to: {num_latent_chunk}")
|
| 1209 |
+
|
| 1210 |
+
if not is_enable_stage2:
|
| 1211 |
+
patch_size = self.transformer.config.patch_size
|
| 1212 |
+
image_seq_len = (
|
| 1213 |
+
num_latent_frames_per_chunk
|
| 1214 |
+
* (height // self.vae_scale_factor_spatial)
|
| 1215 |
+
* (width // self.vae_scale_factor_spatial)
|
| 1216 |
+
// (patch_size[0] * patch_size[1] * patch_size[2])
|
| 1217 |
+
)
|
| 1218 |
+
sigmas = np.linspace(0.999, 0.0, num_inference_steps + 1)[:-1] if sigmas is None else sigmas
|
| 1219 |
+
mu = calculate_shift(
|
| 1220 |
+
image_seq_len,
|
| 1221 |
+
self.scheduler.config.get("base_image_seq_len", 256),
|
| 1222 |
+
self.scheduler.config.get("max_image_seq_len", 4096),
|
| 1223 |
+
self.scheduler.config.get("base_shift", 0.5),
|
| 1224 |
+
self.scheduler.config.get("max_shift", 1.15),
|
| 1225 |
+
)
|
| 1226 |
+
|
| 1227 |
+
for k in range(num_latent_chunk):
|
| 1228 |
+
if use_interpolate_prompt:
|
| 1229 |
+
assert num_latent_chunk >= max(interpolate_cumulative_list)
|
| 1230 |
+
|
| 1231 |
+
current_interval_idx = 0
|
| 1232 |
+
for idx, cumulative_val in enumerate(interpolate_cumulative_list):
|
| 1233 |
+
if k < cumulative_val:
|
| 1234 |
+
current_interval_idx = idx
|
| 1235 |
+
break
|
| 1236 |
+
|
| 1237 |
+
if current_interval_idx == 0:
|
| 1238 |
+
prompt_embeds = all_prompt_embeds[0].unsqueeze(0)
|
| 1239 |
+
else:
|
| 1240 |
+
interval_start = interpolate_cumulative_list[current_interval_idx - 1]
|
| 1241 |
+
position_in_interval = k - interval_start
|
| 1242 |
+
|
| 1243 |
+
if position_in_interval < interpolation_steps:
|
| 1244 |
+
if interpolate_embeds is None or interpolate_interval_idx != current_interval_idx:
|
| 1245 |
+
interpolate_embeds = self.interpolate_prompt_embeds(
|
| 1246 |
+
prompt_embeds_1=all_prompt_embeds[current_interval_idx - 1].unsqueeze(0),
|
| 1247 |
+
prompt_embeds_2=all_prompt_embeds[current_interval_idx].unsqueeze(0),
|
| 1248 |
+
interpolation_steps=interpolation_steps,
|
| 1249 |
+
)
|
| 1250 |
+
interpolate_interval_idx = current_interval_idx
|
| 1251 |
+
|
| 1252 |
+
prompt_embeds = interpolate_embeds[position_in_interval]
|
| 1253 |
+
else:
|
| 1254 |
+
prompt_embeds = all_prompt_embeds[current_interval_idx].unsqueeze(0)
|
| 1255 |
+
else:
|
| 1256 |
+
prompt_embeds = all_prompt_embeds
|
| 1257 |
+
|
| 1258 |
+
is_first_chunk = k == 0
|
| 1259 |
+
is_second_chunk = k == 1
|
| 1260 |
+
if keep_first_frame:
|
| 1261 |
+
latents_history_long, latents_history_mid, latents_history_1x = history_latents[
|
| 1262 |
+
:, :, -num_history_latent_frames:
|
| 1263 |
+
].split(history_sizes, dim=2)
|
| 1264 |
+
if image_latents is None and is_first_chunk:
|
| 1265 |
+
latents_prefix = torch.zeros(
|
| 1266 |
+
(
|
| 1267 |
+
batch_size,
|
| 1268 |
+
num_channels_latents,
|
| 1269 |
+
1,
|
| 1270 |
+
latents_history_1x.shape[-2],
|
| 1271 |
+
latents_history_1x.shape[-1],
|
| 1272 |
+
),
|
| 1273 |
+
device=device,
|
| 1274 |
+
dtype=latents_history_1x.dtype,
|
| 1275 |
+
)
|
| 1276 |
+
else:
|
| 1277 |
+
latents_prefix = image_latents
|
| 1278 |
+
latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2)
|
| 1279 |
+
else:
|
| 1280 |
+
latents_history_long, latents_history_mid, latents_history_short = history_latents[
|
| 1281 |
+
:, :, -num_history_latent_frames:
|
| 1282 |
+
].split(history_sizes, dim=2)
|
| 1283 |
+
|
| 1284 |
+
latents = self.prepare_latents(
|
| 1285 |
+
batch_size,
|
| 1286 |
+
num_channels_latents,
|
| 1287 |
+
height,
|
| 1288 |
+
width,
|
| 1289 |
+
window_num_frames,
|
| 1290 |
+
dtype=torch.float32,
|
| 1291 |
+
device=device,
|
| 1292 |
+
generator=generator,
|
| 1293 |
+
latents=None,
|
| 1294 |
+
)
|
| 1295 |
+
|
| 1296 |
+
if not is_enable_stage2:
|
| 1297 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device, sigmas=sigmas, mu=mu)
|
| 1298 |
+
timesteps = self.scheduler.timesteps
|
| 1299 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 1300 |
+
self._num_timesteps = len(timesteps)
|
| 1301 |
+
else:
|
| 1302 |
+
num_inference_steps = (
|
| 1303 |
+
sum(pyramid_num_inference_steps_list) * 2
|
| 1304 |
+
if is_amplify_first_chunk and self.config.is_distilled and is_first_chunk
|
| 1305 |
+
else sum(pyramid_num_inference_steps_list)
|
| 1306 |
+
)
|
| 1307 |
+
|
| 1308 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 1309 |
+
if is_enable_stage2:
|
| 1310 |
+
latents = self.stage2_sample(
|
| 1311 |
+
latents=latents,
|
| 1312 |
+
pyramid_num_stages=pyramid_num_stages,
|
| 1313 |
+
pyramid_num_inference_steps_list=pyramid_num_inference_steps_list,
|
| 1314 |
+
prompt_embeds=prompt_embeds,
|
| 1315 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1316 |
+
guidance_scale=guidance_scale,
|
| 1317 |
+
indices_hidden_states=indices_hidden_states,
|
| 1318 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1319 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1320 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1321 |
+
latents_history_short=latents_history_short,
|
| 1322 |
+
latents_history_mid=latents_history_mid,
|
| 1323 |
+
latents_history_long=latents_history_long,
|
| 1324 |
+
attention_kwargs=attention_kwargs,
|
| 1325 |
+
device=device,
|
| 1326 |
+
transformer_dtype=transformer_dtype,
|
| 1327 |
+
# ------------ CFG Zero ------------
|
| 1328 |
+
use_zero_init=use_zero_init,
|
| 1329 |
+
zero_steps=zero_steps,
|
| 1330 |
+
# -------------- DMD --------------
|
| 1331 |
+
is_amplify_first_chunk=is_amplify_first_chunk and is_first_chunk,
|
| 1332 |
+
# ------------ Callback ------------
|
| 1333 |
+
callback_on_step_end=callback_on_step_end,
|
| 1334 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1335 |
+
progress_bar=progress_bar,
|
| 1336 |
+
chunk_index=k,
|
| 1337 |
+
relative_l1_records=relative_l1_records,
|
| 1338 |
+
)
|
| 1339 |
+
else:
|
| 1340 |
+
latents = self.stage1_sample(
|
| 1341 |
+
latents=latents,
|
| 1342 |
+
prompt_embeds=prompt_embeds,
|
| 1343 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1344 |
+
timesteps=timesteps,
|
| 1345 |
+
guidance_scale=guidance_scale,
|
| 1346 |
+
indices_hidden_states=indices_hidden_states,
|
| 1347 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1348 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1349 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1350 |
+
latents_history_short=latents_history_short,
|
| 1351 |
+
latents_history_mid=latents_history_mid,
|
| 1352 |
+
latents_history_long=latents_history_long,
|
| 1353 |
+
attention_kwargs=attention_kwargs,
|
| 1354 |
+
device=device,
|
| 1355 |
+
transformer_dtype=transformer_dtype,
|
| 1356 |
+
generator=generator,
|
| 1357 |
+
num_warmup_steps=num_warmup_steps,
|
| 1358 |
+
# ------------ CFG Zero ------------
|
| 1359 |
+
use_zero_init=use_zero_init,
|
| 1360 |
+
zero_steps=zero_steps,
|
| 1361 |
+
# ------------ Callback ------------
|
| 1362 |
+
callback_on_step_end=callback_on_step_end,
|
| 1363 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1364 |
+
progress_bar=progress_bar,
|
| 1365 |
+
chunk_index=k,
|
| 1366 |
+
relative_l1_records=relative_l1_records,
|
| 1367 |
+
)
|
| 1368 |
+
|
| 1369 |
+
if keep_first_frame and (
|
| 1370 |
+
(is_first_chunk and image_latents is None) or (is_skip_first_chunk and is_second_chunk)
|
| 1371 |
+
):
|
| 1372 |
+
image_latents = latents[:, :, 0:1, :, :]
|
| 1373 |
+
|
| 1374 |
+
total_generated_latent_frames += latents.shape[2]
|
| 1375 |
+
history_latents = torch.cat([history_latents, latents], dim=2)
|
| 1376 |
+
real_history_latents = history_latents[:, :, -total_generated_latent_frames:]
|
| 1377 |
+
current_latents = (
|
| 1378 |
+
real_history_latents[:, :, -num_latent_frames_per_chunk:].to(vae_dtype) / latents_std
|
| 1379 |
+
+ latents_mean
|
| 1380 |
+
)
|
| 1381 |
+
current_video = self.vae.decode(current_latents, return_dict=False)[0]
|
| 1382 |
+
|
| 1383 |
+
if history_video is None:
|
| 1384 |
+
history_video = current_video
|
| 1385 |
+
else:
|
| 1386 |
+
history_video = torch.cat([history_video, current_video], dim=2)
|
| 1387 |
+
|
| 1388 |
+
self._current_timestep = None
|
| 1389 |
+
|
| 1390 |
+
if output_type != "latent":
|
| 1391 |
+
generated_frames = history_video.size(2)
|
| 1392 |
+
generated_frames = (
|
| 1393 |
+
generated_frames - 1
|
| 1394 |
+
) // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
|
| 1395 |
+
history_video = history_video[:, :, :generated_frames]
|
| 1396 |
+
video = self.video_processor.postprocess_video(history_video, output_type=output_type)
|
| 1397 |
+
else:
|
| 1398 |
+
video = real_history_latents
|
| 1399 |
+
|
| 1400 |
+
# Offload all models
|
| 1401 |
+
self.maybe_free_model_hooks()
|
| 1402 |
+
|
| 1403 |
+
if not return_dict:
|
| 1404 |
+
return (video,)
|
| 1405 |
+
|
| 1406 |
+
return HeliosPipelineOutput(frames=video, relative_l1=relative_l1_records)
|
Helios/_DEV/helios/diffusers_version/scheduling_helios_diffusers.py
ADDED
|
@@ -0,0 +1,947 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import Literal
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 23 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 24 |
+
from diffusers.utils import BaseOutput, deprecate
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class HeliosSchedulerOutput(BaseOutput):
|
| 29 |
+
prev_sample: torch.FloatTensor
|
| 30 |
+
model_outputs: torch.FloatTensor | None = None
|
| 31 |
+
last_sample: torch.FloatTensor | None = None
|
| 32 |
+
this_order: int | None = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class HeliosScheduler(SchedulerMixin, ConfigMixin):
|
| 36 |
+
_compatibles = []
|
| 37 |
+
order = 1
|
| 38 |
+
|
| 39 |
+
@register_to_config
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
num_train_timesteps: int = 1000,
|
| 43 |
+
shift: float = 1.0, # Following Stable diffusion 3,
|
| 44 |
+
stages: int = 3,
|
| 45 |
+
stage_range: list = [0, 1 / 3, 2 / 3, 1],
|
| 46 |
+
gamma: float = 1 / 3,
|
| 47 |
+
# For UniPC
|
| 48 |
+
thresholding: bool = False,
|
| 49 |
+
prediction_type: str = "flow_prediction",
|
| 50 |
+
solver_order: int = 2,
|
| 51 |
+
predict_x0: bool = True,
|
| 52 |
+
solver_type: str = "bh2",
|
| 53 |
+
lower_order_final: bool = True,
|
| 54 |
+
disable_corrector: list[int] = [],
|
| 55 |
+
solver_p: SchedulerMixin = None,
|
| 56 |
+
use_flow_sigmas: bool = True,
|
| 57 |
+
scheduler_type: str = "unipc", # ["euler", "unipc", "dmd"]
|
| 58 |
+
use_dynamic_shifting: bool = False,
|
| 59 |
+
time_shift_type: Literal["exponential", "linear"] = "linear",
|
| 60 |
+
):
|
| 61 |
+
self.timestep_ratios = {} # The timestep ratio for each stage
|
| 62 |
+
self.timesteps_per_stage = {} # The detailed timesteps per stage (fix max and min per stage)
|
| 63 |
+
self.sigmas_per_stage = {} # always uniform [1000, 0]
|
| 64 |
+
self.start_sigmas = {} # for start point / upsample renoise
|
| 65 |
+
self.end_sigmas = {} # for end point
|
| 66 |
+
self.ori_start_sigmas = {}
|
| 67 |
+
|
| 68 |
+
# self.init_sigmas()
|
| 69 |
+
self.init_sigmas_for_each_stage()
|
| 70 |
+
self.sigma_min = self.sigmas[-1].item()
|
| 71 |
+
self.sigma_max = self.sigmas[0].item()
|
| 72 |
+
self.gamma = gamma
|
| 73 |
+
|
| 74 |
+
if solver_type not in ["bh1", "bh2"]:
|
| 75 |
+
if solver_type in ["midpoint", "heun", "logrho"]:
|
| 76 |
+
self.register_to_config(solver_type="bh2")
|
| 77 |
+
else:
|
| 78 |
+
raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
|
| 79 |
+
|
| 80 |
+
self.predict_x0 = predict_x0
|
| 81 |
+
self.model_outputs = [None] * solver_order
|
| 82 |
+
self.timestep_list = [None] * solver_order
|
| 83 |
+
self.lower_order_nums = 0
|
| 84 |
+
self.disable_corrector = disable_corrector
|
| 85 |
+
self.solver_p = solver_p
|
| 86 |
+
self.last_sample = None
|
| 87 |
+
self._step_index = None
|
| 88 |
+
self._begin_index = None
|
| 89 |
+
|
| 90 |
+
def init_sigmas(self):
|
| 91 |
+
"""
|
| 92 |
+
initialize the global timesteps and sigmas
|
| 93 |
+
"""
|
| 94 |
+
num_train_timesteps = self.config.num_train_timesteps
|
| 95 |
+
shift = self.config.shift
|
| 96 |
+
|
| 97 |
+
alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps + 1)
|
| 98 |
+
sigmas = 1.0 - alphas
|
| 99 |
+
sigmas = np.flip(shift * sigmas / (1 + (shift - 1) * sigmas))[:-1].copy()
|
| 100 |
+
sigmas = torch.from_numpy(sigmas)
|
| 101 |
+
timesteps = (sigmas * num_train_timesteps).clone()
|
| 102 |
+
|
| 103 |
+
self._step_index = None
|
| 104 |
+
self._begin_index = None
|
| 105 |
+
self.timesteps = timesteps
|
| 106 |
+
self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication
|
| 107 |
+
|
| 108 |
+
def init_sigmas_for_each_stage(self):
|
| 109 |
+
"""
|
| 110 |
+
Init the timesteps for each stage
|
| 111 |
+
"""
|
| 112 |
+
self.init_sigmas()
|
| 113 |
+
|
| 114 |
+
stage_distance = []
|
| 115 |
+
stages = self.config.stages
|
| 116 |
+
training_steps = self.config.num_train_timesteps
|
| 117 |
+
stage_range = self.config.stage_range
|
| 118 |
+
|
| 119 |
+
# Init the start and end point of each stage
|
| 120 |
+
for i_s in range(stages):
|
| 121 |
+
# To decide the start and ends point
|
| 122 |
+
start_indice = int(stage_range[i_s] * training_steps)
|
| 123 |
+
start_indice = max(start_indice, 0)
|
| 124 |
+
end_indice = int(stage_range[i_s + 1] * training_steps)
|
| 125 |
+
end_indice = min(end_indice, training_steps)
|
| 126 |
+
start_sigma = self.sigmas[start_indice].item()
|
| 127 |
+
end_sigma = self.sigmas[end_indice].item() if end_indice < training_steps else 0.0
|
| 128 |
+
self.ori_start_sigmas[i_s] = start_sigma
|
| 129 |
+
|
| 130 |
+
if i_s != 0:
|
| 131 |
+
ori_sigma = 1 - start_sigma
|
| 132 |
+
gamma = self.config.gamma
|
| 133 |
+
corrected_sigma = (1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)) * ori_sigma
|
| 134 |
+
# corrected_sigma = 1 / (2 - ori_sigma) * ori_sigma
|
| 135 |
+
start_sigma = 1 - corrected_sigma
|
| 136 |
+
|
| 137 |
+
stage_distance.append(start_sigma - end_sigma)
|
| 138 |
+
self.start_sigmas[i_s] = start_sigma
|
| 139 |
+
self.end_sigmas[i_s] = end_sigma
|
| 140 |
+
|
| 141 |
+
# Determine the ratio of each stage according to flow length
|
| 142 |
+
tot_distance = sum(stage_distance)
|
| 143 |
+
for i_s in range(stages):
|
| 144 |
+
if i_s == 0:
|
| 145 |
+
start_ratio = 0.0
|
| 146 |
+
else:
|
| 147 |
+
start_ratio = sum(stage_distance[:i_s]) / tot_distance
|
| 148 |
+
if i_s == stages - 1:
|
| 149 |
+
end_ratio = 0.9999999999999999
|
| 150 |
+
else:
|
| 151 |
+
end_ratio = sum(stage_distance[: i_s + 1]) / tot_distance
|
| 152 |
+
|
| 153 |
+
self.timestep_ratios[i_s] = (start_ratio, end_ratio)
|
| 154 |
+
|
| 155 |
+
# Determine the timesteps and sigmas for each stage
|
| 156 |
+
for i_s in range(stages):
|
| 157 |
+
timestep_ratio = self.timestep_ratios[i_s]
|
| 158 |
+
# timestep_max = self.timesteps[int(timestep_ratio[0] * training_steps)]
|
| 159 |
+
timestep_max = min(self.timesteps[int(timestep_ratio[0] * training_steps)], 999)
|
| 160 |
+
timestep_min = self.timesteps[min(int(timestep_ratio[1] * training_steps), training_steps - 1)]
|
| 161 |
+
timesteps = np.linspace(timestep_max, timestep_min, training_steps + 1)
|
| 162 |
+
self.timesteps_per_stage[i_s] = (
|
| 163 |
+
timesteps[:-1] if isinstance(timesteps, torch.Tensor) else torch.from_numpy(timesteps[:-1])
|
| 164 |
+
)
|
| 165 |
+
stage_sigmas = np.linspace(0.999, 0, training_steps + 1)
|
| 166 |
+
self.sigmas_per_stage[i_s] = torch.from_numpy(stage_sigmas[:-1])
|
| 167 |
+
|
| 168 |
+
@property
|
| 169 |
+
def step_index(self):
|
| 170 |
+
"""
|
| 171 |
+
The index counter for current timestep. It will increase 1 after each scheduler step.
|
| 172 |
+
"""
|
| 173 |
+
return self._step_index
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def begin_index(self):
|
| 177 |
+
"""
|
| 178 |
+
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
|
| 179 |
+
"""
|
| 180 |
+
return self._begin_index
|
| 181 |
+
|
| 182 |
+
def set_begin_index(self, begin_index: int = 0):
|
| 183 |
+
"""
|
| 184 |
+
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
begin_index (`int`):
|
| 188 |
+
The begin index for the scheduler.
|
| 189 |
+
"""
|
| 190 |
+
self._begin_index = begin_index
|
| 191 |
+
|
| 192 |
+
def _sigma_to_t(self, sigma):
|
| 193 |
+
return sigma * self.config.num_train_timesteps
|
| 194 |
+
|
| 195 |
+
def set_timesteps(
|
| 196 |
+
self,
|
| 197 |
+
num_inference_steps: int,
|
| 198 |
+
stage_index: int | None = None,
|
| 199 |
+
device: str | torch.device = None,
|
| 200 |
+
sigmas: bool | None = None,
|
| 201 |
+
mu: bool | None = None,
|
| 202 |
+
is_amplify_first_chunk: bool = False,
|
| 203 |
+
):
|
| 204 |
+
"""
|
| 205 |
+
Setting the timesteps and sigmas for each stage
|
| 206 |
+
"""
|
| 207 |
+
if self.config.scheduler_type == "dmd":
|
| 208 |
+
if is_amplify_first_chunk:
|
| 209 |
+
num_inference_steps = num_inference_steps * 2 + 1
|
| 210 |
+
else:
|
| 211 |
+
num_inference_steps = num_inference_steps + 1
|
| 212 |
+
|
| 213 |
+
self.num_inference_steps = num_inference_steps
|
| 214 |
+
self.init_sigmas()
|
| 215 |
+
|
| 216 |
+
if self.config.stages == 1:
|
| 217 |
+
if sigmas is None:
|
| 218 |
+
sigmas = np.linspace(1, 1 / self.config.num_train_timesteps, num_inference_steps + 1)[:-1].astype(
|
| 219 |
+
np.float32
|
| 220 |
+
)
|
| 221 |
+
if self.config.shift != 1.0:
|
| 222 |
+
assert not self.config.use_dynamic_shifting
|
| 223 |
+
sigmas = self.time_shift(self.config.shift, 1.0, sigmas)
|
| 224 |
+
timesteps = (sigmas * self.config.num_train_timesteps).copy()
|
| 225 |
+
sigmas = torch.from_numpy(sigmas)
|
| 226 |
+
else:
|
| 227 |
+
stage_timesteps = self.timesteps_per_stage[stage_index]
|
| 228 |
+
timesteps = np.linspace(
|
| 229 |
+
stage_timesteps[0].item(),
|
| 230 |
+
stage_timesteps[-1].item(),
|
| 231 |
+
num_inference_steps,
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
stage_sigmas = self.sigmas_per_stage[stage_index]
|
| 235 |
+
ratios = np.linspace(stage_sigmas[0].item(), stage_sigmas[-1].item(), num_inference_steps)
|
| 236 |
+
sigmas = torch.from_numpy(ratios)
|
| 237 |
+
|
| 238 |
+
self.timesteps = torch.from_numpy(timesteps).to(device=device)
|
| 239 |
+
self.sigmas = torch.cat([sigmas, torch.zeros(1)]).to(device=device)
|
| 240 |
+
|
| 241 |
+
self._step_index = None
|
| 242 |
+
self.reset_scheduler_history()
|
| 243 |
+
|
| 244 |
+
if self.config.scheduler_type == "dmd":
|
| 245 |
+
self.timesteps = self.timesteps[:-1]
|
| 246 |
+
self.sigmas = torch.cat([self.sigmas[:-2], self.sigmas[-1:]])
|
| 247 |
+
|
| 248 |
+
if self.config.use_dynamic_shifting:
|
| 249 |
+
assert self.config.shift == 1.0
|
| 250 |
+
self.sigmas = self.time_shift(mu, 1.0, self.sigmas)
|
| 251 |
+
if self.config.stages == 1:
|
| 252 |
+
self.timesteps = self.sigmas[:-1] * self.config.num_train_timesteps
|
| 253 |
+
else:
|
| 254 |
+
self.timesteps = self.timesteps_per_stage[stage_index].min() + self.sigmas[:-1] * (
|
| 255 |
+
self.timesteps_per_stage[stage_index].max() - self.timesteps_per_stage[stage_index].min()
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
# Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler.time_shift
|
| 259 |
+
def time_shift(self, mu: float, sigma: float, t: torch.Tensor):
|
| 260 |
+
"""
|
| 261 |
+
Apply time shifting to the sigmas.
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
mu (`float`):
|
| 265 |
+
The mu parameter for the time shift.
|
| 266 |
+
sigma (`float`):
|
| 267 |
+
The sigma parameter for the time shift.
|
| 268 |
+
t (`torch.Tensor`):
|
| 269 |
+
The input timesteps.
|
| 270 |
+
|
| 271 |
+
Returns:
|
| 272 |
+
`torch.Tensor`:
|
| 273 |
+
The time-shifted timesteps.
|
| 274 |
+
"""
|
| 275 |
+
if self.config.time_shift_type == "exponential":
|
| 276 |
+
return self._time_shift_exponential(mu, sigma, t)
|
| 277 |
+
elif self.config.time_shift_type == "linear":
|
| 278 |
+
return self._time_shift_linear(mu, sigma, t)
|
| 279 |
+
|
| 280 |
+
# Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._time_shift_exponential
|
| 281 |
+
def _time_shift_exponential(self, mu, sigma, t):
|
| 282 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
| 283 |
+
|
| 284 |
+
# Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._time_shift_linear
|
| 285 |
+
def _time_shift_linear(self, mu, sigma, t):
|
| 286 |
+
return mu / (mu + (1 / t - 1) ** sigma)
|
| 287 |
+
|
| 288 |
+
# ---------------------------------- Euler ----------------------------------
|
| 289 |
+
def index_for_timestep(self, timestep, schedule_timesteps=None):
|
| 290 |
+
if schedule_timesteps is None:
|
| 291 |
+
schedule_timesteps = self.timesteps
|
| 292 |
+
|
| 293 |
+
indices = (schedule_timesteps == timestep).nonzero()
|
| 294 |
+
|
| 295 |
+
# The sigma index that is taken for the **very** first `step`
|
| 296 |
+
# is always the second index (or the last index if there is only 1)
|
| 297 |
+
# This way we can ensure we don't accidentally skip a sigma in
|
| 298 |
+
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
|
| 299 |
+
pos = 1 if len(indices) > 1 else 0
|
| 300 |
+
|
| 301 |
+
return indices[pos].item()
|
| 302 |
+
|
| 303 |
+
def _init_step_index(self, timestep):
|
| 304 |
+
if self.begin_index is None:
|
| 305 |
+
if isinstance(timestep, torch.Tensor):
|
| 306 |
+
timestep = timestep.to(self.timesteps.device)
|
| 307 |
+
self._step_index = self.index_for_timestep(timestep)
|
| 308 |
+
else:
|
| 309 |
+
self._step_index = self._begin_index
|
| 310 |
+
|
| 311 |
+
def step_euler(
|
| 312 |
+
self,
|
| 313 |
+
model_output: torch.FloatTensor,
|
| 314 |
+
timestep: float | torch.FloatTensor = None,
|
| 315 |
+
sample: torch.FloatTensor = None,
|
| 316 |
+
generator: torch.Generator | None = None,
|
| 317 |
+
sigma: torch.FloatTensor | None = None,
|
| 318 |
+
sigma_next: torch.FloatTensor | None = None,
|
| 319 |
+
return_dict: bool = True,
|
| 320 |
+
) -> HeliosSchedulerOutput | tuple:
|
| 321 |
+
assert (sigma is None) == (sigma_next is None), "sigma and sigma_next must both be None or both be not None"
|
| 322 |
+
|
| 323 |
+
if sigma is None and sigma_next is None:
|
| 324 |
+
if (
|
| 325 |
+
isinstance(timestep, int)
|
| 326 |
+
or isinstance(timestep, torch.IntTensor)
|
| 327 |
+
or isinstance(timestep, torch.LongTensor)
|
| 328 |
+
):
|
| 329 |
+
raise ValueError(
|
| 330 |
+
(
|
| 331 |
+
"Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
|
| 332 |
+
" `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
|
| 333 |
+
" one of the `scheduler.timesteps` as a timestep."
|
| 334 |
+
),
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
if self.step_index is None:
|
| 338 |
+
self._step_index = 0
|
| 339 |
+
|
| 340 |
+
# Upcast to avoid precision issues when computing prev_sample
|
| 341 |
+
sample = sample.to(torch.float32)
|
| 342 |
+
|
| 343 |
+
if sigma is None and sigma_next is None:
|
| 344 |
+
sigma = self.sigmas[self.step_index]
|
| 345 |
+
sigma_next = self.sigmas[self.step_index + 1]
|
| 346 |
+
|
| 347 |
+
prev_sample = sample + (sigma_next - sigma) * model_output
|
| 348 |
+
|
| 349 |
+
# Cast sample back to model compatible dtype
|
| 350 |
+
prev_sample = prev_sample.to(model_output.dtype)
|
| 351 |
+
|
| 352 |
+
# upon completion increase step index by one
|
| 353 |
+
self._step_index += 1
|
| 354 |
+
|
| 355 |
+
if not return_dict:
|
| 356 |
+
return (prev_sample,)
|
| 357 |
+
|
| 358 |
+
return HeliosSchedulerOutput(prev_sample=prev_sample)
|
| 359 |
+
|
| 360 |
+
# ---------------------------------- UniPC ----------------------------------
|
| 361 |
+
def _sigma_to_alpha_sigma_t(self, sigma):
|
| 362 |
+
if self.config.use_flow_sigmas:
|
| 363 |
+
alpha_t = 1 - sigma
|
| 364 |
+
sigma_t = torch.clamp(sigma, min=1e-8)
|
| 365 |
+
else:
|
| 366 |
+
alpha_t = 1 / ((sigma**2 + 1) ** 0.5)
|
| 367 |
+
sigma_t = sigma * alpha_t
|
| 368 |
+
|
| 369 |
+
return alpha_t, sigma_t
|
| 370 |
+
|
| 371 |
+
def convert_model_output(
|
| 372 |
+
self,
|
| 373 |
+
model_output: torch.Tensor,
|
| 374 |
+
*args,
|
| 375 |
+
sample: torch.Tensor = None,
|
| 376 |
+
sigma: torch.Tensor = None,
|
| 377 |
+
**kwargs,
|
| 378 |
+
) -> torch.Tensor:
|
| 379 |
+
r"""
|
| 380 |
+
Convert the model output to the corresponding type the UniPC algorithm needs.
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
model_output (`torch.Tensor`):
|
| 384 |
+
The direct output from the learned diffusion model.
|
| 385 |
+
timestep (`int`):
|
| 386 |
+
The current discrete timestep in the diffusion chain.
|
| 387 |
+
sample (`torch.Tensor`):
|
| 388 |
+
A current instance of a sample created by the diffusion process.
|
| 389 |
+
|
| 390 |
+
Returns:
|
| 391 |
+
`torch.Tensor`:
|
| 392 |
+
The converted model output.
|
| 393 |
+
"""
|
| 394 |
+
timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
|
| 395 |
+
if sample is None:
|
| 396 |
+
if len(args) > 1:
|
| 397 |
+
sample = args[1]
|
| 398 |
+
else:
|
| 399 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 400 |
+
if timestep is not None:
|
| 401 |
+
deprecate(
|
| 402 |
+
"timesteps",
|
| 403 |
+
"1.0.0",
|
| 404 |
+
"Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
flag = False
|
| 408 |
+
if sigma is None:
|
| 409 |
+
flag = True
|
| 410 |
+
sigma = self.sigmas[self.step_index]
|
| 411 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
|
| 412 |
+
|
| 413 |
+
if self.predict_x0:
|
| 414 |
+
if self.config.prediction_type == "epsilon":
|
| 415 |
+
x0_pred = (sample - sigma_t * model_output) / alpha_t
|
| 416 |
+
elif self.config.prediction_type == "sample":
|
| 417 |
+
x0_pred = model_output
|
| 418 |
+
elif self.config.prediction_type == "v_prediction":
|
| 419 |
+
x0_pred = alpha_t * sample - sigma_t * model_output
|
| 420 |
+
elif self.config.prediction_type == "flow_prediction":
|
| 421 |
+
if flag:
|
| 422 |
+
sigma_t = self.sigmas[self.step_index]
|
| 423 |
+
else:
|
| 424 |
+
sigma_t = sigma
|
| 425 |
+
x0_pred = sample - sigma_t * model_output
|
| 426 |
+
else:
|
| 427 |
+
raise ValueError(
|
| 428 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, "
|
| 429 |
+
"`v_prediction`, or `flow_prediction` for the UniPCMultistepScheduler."
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
if self.config.thresholding:
|
| 433 |
+
x0_pred = self._threshold_sample(x0_pred)
|
| 434 |
+
|
| 435 |
+
return x0_pred
|
| 436 |
+
else:
|
| 437 |
+
if self.config.prediction_type == "epsilon":
|
| 438 |
+
return model_output
|
| 439 |
+
elif self.config.prediction_type == "sample":
|
| 440 |
+
epsilon = (sample - alpha_t * model_output) / sigma_t
|
| 441 |
+
return epsilon
|
| 442 |
+
elif self.config.prediction_type == "v_prediction":
|
| 443 |
+
epsilon = alpha_t * model_output + sigma_t * sample
|
| 444 |
+
return epsilon
|
| 445 |
+
else:
|
| 446 |
+
raise ValueError(
|
| 447 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
|
| 448 |
+
" `v_prediction` for the UniPCMultistepScheduler."
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
def multistep_uni_p_bh_update(
|
| 452 |
+
self,
|
| 453 |
+
model_output: torch.Tensor,
|
| 454 |
+
*args,
|
| 455 |
+
sample: torch.Tensor = None,
|
| 456 |
+
order: int = None,
|
| 457 |
+
sigma: torch.Tensor = None,
|
| 458 |
+
sigma_next: torch.Tensor = None,
|
| 459 |
+
**kwargs,
|
| 460 |
+
) -> torch.Tensor:
|
| 461 |
+
"""
|
| 462 |
+
One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified.
|
| 463 |
+
|
| 464 |
+
Args:
|
| 465 |
+
model_output (`torch.Tensor`):
|
| 466 |
+
The direct output from the learned diffusion model at the current timestep.
|
| 467 |
+
prev_timestep (`int`):
|
| 468 |
+
The previous discrete timestep in the diffusion chain.
|
| 469 |
+
sample (`torch.Tensor`):
|
| 470 |
+
A current instance of a sample created by the diffusion process.
|
| 471 |
+
order (`int`):
|
| 472 |
+
The order of UniP at this timestep (corresponds to the *p* in UniPC-p).
|
| 473 |
+
|
| 474 |
+
Returns:
|
| 475 |
+
`torch.Tensor`:
|
| 476 |
+
The sample tensor at the previous timestep.
|
| 477 |
+
"""
|
| 478 |
+
prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None)
|
| 479 |
+
if sample is None:
|
| 480 |
+
if len(args) > 1:
|
| 481 |
+
sample = args[1]
|
| 482 |
+
else:
|
| 483 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 484 |
+
if order is None:
|
| 485 |
+
if len(args) > 2:
|
| 486 |
+
order = args[2]
|
| 487 |
+
else:
|
| 488 |
+
raise ValueError("missing `order` as a required keyword argument")
|
| 489 |
+
if prev_timestep is not None:
|
| 490 |
+
deprecate(
|
| 491 |
+
"prev_timestep",
|
| 492 |
+
"1.0.0",
|
| 493 |
+
"Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 494 |
+
)
|
| 495 |
+
model_output_list = self.model_outputs
|
| 496 |
+
|
| 497 |
+
s0 = self.timestep_list[-1]
|
| 498 |
+
m0 = model_output_list[-1]
|
| 499 |
+
x = sample
|
| 500 |
+
|
| 501 |
+
if self.solver_p:
|
| 502 |
+
x_t = self.solver_p.step(model_output, s0, x).prev_sample
|
| 503 |
+
return x_t
|
| 504 |
+
|
| 505 |
+
if sigma_next is None and sigma is None:
|
| 506 |
+
sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
|
| 507 |
+
else:
|
| 508 |
+
sigma_t, sigma_s0 = sigma_next, sigma
|
| 509 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 510 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 511 |
+
|
| 512 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 513 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 514 |
+
|
| 515 |
+
h = lambda_t - lambda_s0
|
| 516 |
+
device = sample.device
|
| 517 |
+
|
| 518 |
+
rks = []
|
| 519 |
+
D1s = []
|
| 520 |
+
for i in range(1, order):
|
| 521 |
+
si = self.step_index - i
|
| 522 |
+
mi = model_output_list[-(i + 1)]
|
| 523 |
+
alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
|
| 524 |
+
lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
|
| 525 |
+
rk = (lambda_si - lambda_s0) / h
|
| 526 |
+
rks.append(rk)
|
| 527 |
+
D1s.append((mi - m0) / rk)
|
| 528 |
+
|
| 529 |
+
rks.append(1.0)
|
| 530 |
+
rks = torch.tensor(rks, device=device)
|
| 531 |
+
|
| 532 |
+
R = []
|
| 533 |
+
b = []
|
| 534 |
+
|
| 535 |
+
hh = -h if self.predict_x0 else h
|
| 536 |
+
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
| 537 |
+
h_phi_k = h_phi_1 / hh - 1
|
| 538 |
+
|
| 539 |
+
factorial_i = 1
|
| 540 |
+
|
| 541 |
+
if self.config.solver_type == "bh1":
|
| 542 |
+
B_h = hh
|
| 543 |
+
elif self.config.solver_type == "bh2":
|
| 544 |
+
B_h = torch.expm1(hh)
|
| 545 |
+
else:
|
| 546 |
+
raise NotImplementedError()
|
| 547 |
+
|
| 548 |
+
for i in range(1, order + 1):
|
| 549 |
+
R.append(torch.pow(rks, i - 1))
|
| 550 |
+
b.append(h_phi_k * factorial_i / B_h)
|
| 551 |
+
factorial_i *= i + 1
|
| 552 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
| 553 |
+
|
| 554 |
+
R = torch.stack(R)
|
| 555 |
+
b = torch.tensor(b, device=device)
|
| 556 |
+
|
| 557 |
+
if len(D1s) > 0:
|
| 558 |
+
D1s = torch.stack(D1s, dim=1) # (B, K)
|
| 559 |
+
# for order 2, we use a simplified version
|
| 560 |
+
if order == 2:
|
| 561 |
+
rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device)
|
| 562 |
+
else:
|
| 563 |
+
rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]).to(device).to(x.dtype)
|
| 564 |
+
else:
|
| 565 |
+
D1s = None
|
| 566 |
+
|
| 567 |
+
if self.predict_x0:
|
| 568 |
+
x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
|
| 569 |
+
if D1s is not None:
|
| 570 |
+
pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s)
|
| 571 |
+
else:
|
| 572 |
+
pred_res = 0
|
| 573 |
+
x_t = x_t_ - alpha_t * B_h * pred_res
|
| 574 |
+
else:
|
| 575 |
+
x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
|
| 576 |
+
if D1s is not None:
|
| 577 |
+
pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s)
|
| 578 |
+
else:
|
| 579 |
+
pred_res = 0
|
| 580 |
+
x_t = x_t_ - sigma_t * B_h * pred_res
|
| 581 |
+
|
| 582 |
+
x_t = x_t.to(x.dtype)
|
| 583 |
+
return x_t
|
| 584 |
+
|
| 585 |
+
def multistep_uni_c_bh_update(
|
| 586 |
+
self,
|
| 587 |
+
this_model_output: torch.Tensor,
|
| 588 |
+
*args,
|
| 589 |
+
last_sample: torch.Tensor = None,
|
| 590 |
+
this_sample: torch.Tensor = None,
|
| 591 |
+
order: int = None,
|
| 592 |
+
sigma_before: torch.Tensor = None,
|
| 593 |
+
sigma: torch.Tensor = None,
|
| 594 |
+
**kwargs,
|
| 595 |
+
) -> torch.Tensor:
|
| 596 |
+
"""
|
| 597 |
+
One step for the UniC (B(h) version).
|
| 598 |
+
|
| 599 |
+
Args:
|
| 600 |
+
this_model_output (`torch.Tensor`):
|
| 601 |
+
The model outputs at `x_t`.
|
| 602 |
+
this_timestep (`int`):
|
| 603 |
+
The current timestep `t`.
|
| 604 |
+
last_sample (`torch.Tensor`):
|
| 605 |
+
The generated sample before the last predictor `x_{t-1}`.
|
| 606 |
+
this_sample (`torch.Tensor`):
|
| 607 |
+
The generated sample after the last predictor `x_{t}`.
|
| 608 |
+
order (`int`):
|
| 609 |
+
The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`.
|
| 610 |
+
|
| 611 |
+
Returns:
|
| 612 |
+
`torch.Tensor`:
|
| 613 |
+
The corrected sample tensor at the current timestep.
|
| 614 |
+
"""
|
| 615 |
+
this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None)
|
| 616 |
+
if last_sample is None:
|
| 617 |
+
if len(args) > 1:
|
| 618 |
+
last_sample = args[1]
|
| 619 |
+
else:
|
| 620 |
+
raise ValueError("missing `last_sample` as a required keyword argument")
|
| 621 |
+
if this_sample is None:
|
| 622 |
+
if len(args) > 2:
|
| 623 |
+
this_sample = args[2]
|
| 624 |
+
else:
|
| 625 |
+
raise ValueError("missing `this_sample` as a required keyword argument")
|
| 626 |
+
if order is None:
|
| 627 |
+
if len(args) > 3:
|
| 628 |
+
order = args[3]
|
| 629 |
+
else:
|
| 630 |
+
raise ValueError("missing `order` as a required keyword argument")
|
| 631 |
+
if this_timestep is not None:
|
| 632 |
+
deprecate(
|
| 633 |
+
"this_timestep",
|
| 634 |
+
"1.0.0",
|
| 635 |
+
"Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
model_output_list = self.model_outputs
|
| 639 |
+
|
| 640 |
+
m0 = model_output_list[-1]
|
| 641 |
+
x = last_sample
|
| 642 |
+
x_t = this_sample
|
| 643 |
+
model_t = this_model_output
|
| 644 |
+
|
| 645 |
+
if sigma_before is None and sigma is None:
|
| 646 |
+
sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1]
|
| 647 |
+
else:
|
| 648 |
+
sigma_t, sigma_s0 = sigma, sigma_before
|
| 649 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 650 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 651 |
+
|
| 652 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 653 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 654 |
+
|
| 655 |
+
h = lambda_t - lambda_s0
|
| 656 |
+
device = this_sample.device
|
| 657 |
+
|
| 658 |
+
rks = []
|
| 659 |
+
D1s = []
|
| 660 |
+
for i in range(1, order):
|
| 661 |
+
si = self.step_index - (i + 1)
|
| 662 |
+
mi = model_output_list[-(i + 1)]
|
| 663 |
+
alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
|
| 664 |
+
lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
|
| 665 |
+
rk = (lambda_si - lambda_s0) / h
|
| 666 |
+
rks.append(rk)
|
| 667 |
+
D1s.append((mi - m0) / rk)
|
| 668 |
+
|
| 669 |
+
rks.append(1.0)
|
| 670 |
+
rks = torch.tensor(rks, device=device)
|
| 671 |
+
|
| 672 |
+
R = []
|
| 673 |
+
b = []
|
| 674 |
+
|
| 675 |
+
hh = -h if self.predict_x0 else h
|
| 676 |
+
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
| 677 |
+
h_phi_k = h_phi_1 / hh - 1
|
| 678 |
+
|
| 679 |
+
factorial_i = 1
|
| 680 |
+
|
| 681 |
+
if self.config.solver_type == "bh1":
|
| 682 |
+
B_h = hh
|
| 683 |
+
elif self.config.solver_type == "bh2":
|
| 684 |
+
B_h = torch.expm1(hh)
|
| 685 |
+
else:
|
| 686 |
+
raise NotImplementedError()
|
| 687 |
+
|
| 688 |
+
for i in range(1, order + 1):
|
| 689 |
+
R.append(torch.pow(rks, i - 1))
|
| 690 |
+
b.append(h_phi_k * factorial_i / B_h)
|
| 691 |
+
factorial_i *= i + 1
|
| 692 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
| 693 |
+
|
| 694 |
+
R = torch.stack(R)
|
| 695 |
+
b = torch.tensor(b, device=device)
|
| 696 |
+
|
| 697 |
+
if len(D1s) > 0:
|
| 698 |
+
D1s = torch.stack(D1s, dim=1)
|
| 699 |
+
else:
|
| 700 |
+
D1s = None
|
| 701 |
+
|
| 702 |
+
# for order 1, we use a simplified version
|
| 703 |
+
if order == 1:
|
| 704 |
+
rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device)
|
| 705 |
+
else:
|
| 706 |
+
rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype)
|
| 707 |
+
|
| 708 |
+
if self.predict_x0:
|
| 709 |
+
x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
|
| 710 |
+
if D1s is not None:
|
| 711 |
+
corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
|
| 712 |
+
else:
|
| 713 |
+
corr_res = 0
|
| 714 |
+
D1_t = model_t - m0
|
| 715 |
+
x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t)
|
| 716 |
+
else:
|
| 717 |
+
x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
|
| 718 |
+
if D1s is not None:
|
| 719 |
+
corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
|
| 720 |
+
else:
|
| 721 |
+
corr_res = 0
|
| 722 |
+
D1_t = model_t - m0
|
| 723 |
+
x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t)
|
| 724 |
+
x_t = x_t.to(x.dtype)
|
| 725 |
+
return x_t
|
| 726 |
+
|
| 727 |
+
def step_unipc(
|
| 728 |
+
self,
|
| 729 |
+
model_output: torch.Tensor,
|
| 730 |
+
timestep: int | torch.Tensor = None,
|
| 731 |
+
sample: torch.Tensor = None,
|
| 732 |
+
return_dict: bool = True,
|
| 733 |
+
model_outputs: list = None,
|
| 734 |
+
timestep_list: list = None,
|
| 735 |
+
sigma_before: torch.Tensor = None,
|
| 736 |
+
sigma: torch.Tensor = None,
|
| 737 |
+
sigma_next: torch.Tensor = None,
|
| 738 |
+
cus_step_index: int = None,
|
| 739 |
+
cus_lower_order_num: int = None,
|
| 740 |
+
cus_this_order: int = None,
|
| 741 |
+
cus_last_sample: torch.Tensor = None,
|
| 742 |
+
) -> HeliosSchedulerOutput | tuple:
|
| 743 |
+
if self.num_inference_steps is None:
|
| 744 |
+
raise ValueError(
|
| 745 |
+
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
if cus_step_index is None:
|
| 749 |
+
if self.step_index is None:
|
| 750 |
+
self._step_index = 0
|
| 751 |
+
else:
|
| 752 |
+
self._step_index = cus_step_index
|
| 753 |
+
|
| 754 |
+
if cus_lower_order_num is not None:
|
| 755 |
+
self.lower_order_nums = cus_lower_order_num
|
| 756 |
+
|
| 757 |
+
if cus_this_order is not None:
|
| 758 |
+
self.this_order = cus_this_order
|
| 759 |
+
|
| 760 |
+
if cus_last_sample is not None:
|
| 761 |
+
self.last_sample = cus_last_sample
|
| 762 |
+
|
| 763 |
+
use_corrector = (
|
| 764 |
+
self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
# Convert model output using the proper conversion method
|
| 768 |
+
model_output_convert = self.convert_model_output(model_output, sample=sample, sigma=sigma)
|
| 769 |
+
|
| 770 |
+
if model_outputs is not None and timestep_list is not None:
|
| 771 |
+
self.model_outputs = model_outputs[:-1]
|
| 772 |
+
self.timestep_list = timestep_list[:-1]
|
| 773 |
+
|
| 774 |
+
if use_corrector:
|
| 775 |
+
sample = self.multistep_uni_c_bh_update(
|
| 776 |
+
this_model_output=model_output_convert,
|
| 777 |
+
last_sample=self.last_sample,
|
| 778 |
+
this_sample=sample,
|
| 779 |
+
order=self.this_order,
|
| 780 |
+
sigma_before=sigma_before,
|
| 781 |
+
sigma=sigma,
|
| 782 |
+
)
|
| 783 |
+
|
| 784 |
+
if model_outputs is not None and timestep_list is not None:
|
| 785 |
+
model_outputs[-1] = model_output_convert
|
| 786 |
+
self.model_outputs = model_outputs[1:]
|
| 787 |
+
self.timestep_list = timestep_list[1:]
|
| 788 |
+
else:
|
| 789 |
+
for i in range(self.config.solver_order - 1):
|
| 790 |
+
self.model_outputs[i] = self.model_outputs[i + 1]
|
| 791 |
+
self.timestep_list[i] = self.timestep_list[i + 1]
|
| 792 |
+
self.model_outputs[-1] = model_output_convert
|
| 793 |
+
self.timestep_list[-1] = timestep
|
| 794 |
+
|
| 795 |
+
if self.config.lower_order_final:
|
| 796 |
+
this_order = min(self.config.solver_order, len(self.timesteps) - self.step_index)
|
| 797 |
+
else:
|
| 798 |
+
this_order = self.config.solver_order
|
| 799 |
+
self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep
|
| 800 |
+
assert self.this_order > 0
|
| 801 |
+
|
| 802 |
+
self.last_sample = sample
|
| 803 |
+
prev_sample = self.multistep_uni_p_bh_update(
|
| 804 |
+
model_output=model_output, # pass the original non-converted model output, in case solver-p is used
|
| 805 |
+
sample=sample,
|
| 806 |
+
order=self.this_order,
|
| 807 |
+
sigma=sigma,
|
| 808 |
+
sigma_next=sigma_next,
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
if cus_lower_order_num is None:
|
| 812 |
+
if self.lower_order_nums < self.config.solver_order:
|
| 813 |
+
self.lower_order_nums += 1
|
| 814 |
+
|
| 815 |
+
# upon completion increase step index by one
|
| 816 |
+
if cus_step_index is None:
|
| 817 |
+
self._step_index += 1
|
| 818 |
+
|
| 819 |
+
if not return_dict:
|
| 820 |
+
return (prev_sample, model_outputs, self.last_sample, self.this_order)
|
| 821 |
+
|
| 822 |
+
return HeliosSchedulerOutput(
|
| 823 |
+
prev_sample=prev_sample,
|
| 824 |
+
model_outputs=model_outputs,
|
| 825 |
+
last_sample=self.last_sample,
|
| 826 |
+
this_order=self.this_order,
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
# ---------------------------------- For DMD ----------------------------------
|
| 830 |
+
def add_noise(self, original_samples, noise, timestep, sigmas, timesteps):
|
| 831 |
+
sigmas = sigmas.to(noise.device)
|
| 832 |
+
timesteps = timesteps.to(noise.device)
|
| 833 |
+
timestep_id = torch.argmin((timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1)
|
| 834 |
+
sigma = sigmas[timestep_id].reshape(-1, 1, 1, 1, 1)
|
| 835 |
+
sample = (1 - sigma) * original_samples + sigma * noise
|
| 836 |
+
return sample.type_as(noise)
|
| 837 |
+
|
| 838 |
+
def convert_flow_pred_to_x0(self, flow_pred, xt, timestep, sigmas, timesteps):
|
| 839 |
+
# use higher precision for calculations
|
| 840 |
+
original_dtype = flow_pred.dtype
|
| 841 |
+
device = flow_pred.device
|
| 842 |
+
flow_pred, xt, sigmas, timesteps = (x.double().to(device) for x in (flow_pred, xt, sigmas, timesteps))
|
| 843 |
+
|
| 844 |
+
timestep_id = torch.argmin((timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1)
|
| 845 |
+
sigma_t = sigmas[timestep_id].reshape(-1, 1, 1, 1, 1)
|
| 846 |
+
x0_pred = xt - sigma_t * flow_pred
|
| 847 |
+
return x0_pred.to(original_dtype)
|
| 848 |
+
|
| 849 |
+
def step_dmd(
|
| 850 |
+
self,
|
| 851 |
+
model_output: torch.FloatTensor,
|
| 852 |
+
timestep: float | torch.FloatTensor = None,
|
| 853 |
+
sample: torch.FloatTensor = None,
|
| 854 |
+
generator: torch.Generator | None = None,
|
| 855 |
+
return_dict: bool = True,
|
| 856 |
+
cur_sampling_step: int = 0,
|
| 857 |
+
dmd_noisy_tensor: torch.FloatTensor | None = None,
|
| 858 |
+
dmd_sigmas: torch.FloatTensor | None = None,
|
| 859 |
+
dmd_timesteps: torch.FloatTensor | None = None,
|
| 860 |
+
all_timesteps: torch.FloatTensor | None = None,
|
| 861 |
+
):
|
| 862 |
+
pred_image_or_video = self.convert_flow_pred_to_x0(
|
| 863 |
+
flow_pred=model_output,
|
| 864 |
+
xt=sample,
|
| 865 |
+
timestep=torch.full((model_output.shape[0],), timestep, dtype=torch.long, device=model_output.device),
|
| 866 |
+
sigmas=dmd_sigmas,
|
| 867 |
+
timesteps=dmd_timesteps,
|
| 868 |
+
)
|
| 869 |
+
if cur_sampling_step < len(all_timesteps) - 1:
|
| 870 |
+
prev_sample = self.add_noise(
|
| 871 |
+
pred_image_or_video,
|
| 872 |
+
dmd_noisy_tensor,
|
| 873 |
+
torch.full(
|
| 874 |
+
(model_output.shape[0],),
|
| 875 |
+
all_timesteps[cur_sampling_step + 1],
|
| 876 |
+
dtype=torch.long,
|
| 877 |
+
device=model_output.device,
|
| 878 |
+
),
|
| 879 |
+
sigmas=dmd_sigmas,
|
| 880 |
+
timesteps=dmd_timesteps,
|
| 881 |
+
)
|
| 882 |
+
else:
|
| 883 |
+
prev_sample = pred_image_or_video
|
| 884 |
+
|
| 885 |
+
if not return_dict:
|
| 886 |
+
return (prev_sample,)
|
| 887 |
+
|
| 888 |
+
return HeliosSchedulerOutput(prev_sample=prev_sample)
|
| 889 |
+
|
| 890 |
+
# ---------------------------------- Merge ----------------------------------
|
| 891 |
+
def step(
|
| 892 |
+
self,
|
| 893 |
+
model_output: torch.FloatTensor,
|
| 894 |
+
timestep: float | torch.FloatTensor = None,
|
| 895 |
+
sample: torch.FloatTensor = None,
|
| 896 |
+
generator: torch.Generator | None = None,
|
| 897 |
+
return_dict: bool = True,
|
| 898 |
+
# For DMD
|
| 899 |
+
cur_sampling_step: int = 0,
|
| 900 |
+
dmd_noisy_tensor: torch.FloatTensor | None = None,
|
| 901 |
+
dmd_sigmas: torch.FloatTensor | None = None,
|
| 902 |
+
dmd_timesteps: torch.FloatTensor | None = None,
|
| 903 |
+
all_timesteps: torch.FloatTensor | None = None,
|
| 904 |
+
) -> HeliosSchedulerOutput | tuple:
|
| 905 |
+
if self.config.scheduler_type == "euler":
|
| 906 |
+
return self.step_euler(
|
| 907 |
+
model_output=model_output,
|
| 908 |
+
timestep=timestep,
|
| 909 |
+
sample=sample,
|
| 910 |
+
generator=generator,
|
| 911 |
+
return_dict=return_dict,
|
| 912 |
+
)
|
| 913 |
+
elif self.config.scheduler_type == "unipc":
|
| 914 |
+
return self.step_unipc(
|
| 915 |
+
model_output=model_output,
|
| 916 |
+
timestep=timestep,
|
| 917 |
+
sample=sample,
|
| 918 |
+
return_dict=return_dict,
|
| 919 |
+
)
|
| 920 |
+
elif self.config.scheduler_type == "dmd":
|
| 921 |
+
return self.step_dmd(
|
| 922 |
+
model_output=model_output,
|
| 923 |
+
timestep=timestep,
|
| 924 |
+
sample=sample,
|
| 925 |
+
generator=generator,
|
| 926 |
+
return_dict=return_dict,
|
| 927 |
+
cur_sampling_step=cur_sampling_step,
|
| 928 |
+
dmd_noisy_tensor=dmd_noisy_tensor,
|
| 929 |
+
dmd_sigmas=dmd_sigmas,
|
| 930 |
+
dmd_timesteps=dmd_timesteps,
|
| 931 |
+
all_timesteps=all_timesteps,
|
| 932 |
+
)
|
| 933 |
+
else:
|
| 934 |
+
raise NotImplementedError
|
| 935 |
+
|
| 936 |
+
def reset_scheduler_history(self):
|
| 937 |
+
self.model_outputs = [None] * self.config.solver_order
|
| 938 |
+
self.timestep_list = [None] * self.config.solver_order
|
| 939 |
+
self.lower_order_nums = 0
|
| 940 |
+
self.disable_corrector = self.config.disable_corrector
|
| 941 |
+
self.solver_p = self.config.solver_p
|
| 942 |
+
self.last_sample = None
|
| 943 |
+
self._step_index = None
|
| 944 |
+
self._begin_index = None
|
| 945 |
+
|
| 946 |
+
def __len__(self):
|
| 947 |
+
return self.config.num_train_timesteps
|
Helios/_DEV/helios/diffusers_version/transformer_helios_diffusers.py
ADDED
|
@@ -0,0 +1,825 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from functools import lru_cache
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
|
| 23 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 24 |
+
from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
|
| 25 |
+
from diffusers.models._modeling_parallel import ContextParallelInput, ContextParallelOutput
|
| 26 |
+
from diffusers.models.attention import AttentionMixin, AttentionModuleMixin, FeedForward
|
| 27 |
+
from diffusers.models.attention_dispatch import dispatch_attention_fn
|
| 28 |
+
from diffusers.models.cache_utils import CacheMixin
|
| 29 |
+
from diffusers.models.embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps
|
| 30 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 31 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 32 |
+
from diffusers.models.normalization import FP32LayerNorm
|
| 33 |
+
from diffusers.utils import apply_lora_scale, logging
|
| 34 |
+
from diffusers.utils.torch_utils import maybe_allow_in_graph
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def pad_for_3d_conv(x, kernel_size):
|
| 41 |
+
b, c, t, h, w = x.shape
|
| 42 |
+
pt, ph, pw = kernel_size
|
| 43 |
+
pad_t = (pt - (t % pt)) % pt
|
| 44 |
+
pad_h = (ph - (h % ph)) % ph
|
| 45 |
+
pad_w = (pw - (w % pw)) % pw
|
| 46 |
+
return torch.nn.functional.pad(x, (0, pad_w, 0, pad_h, 0, pad_t), mode="replicate")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def center_down_sample_3d(x, kernel_size):
|
| 50 |
+
return torch.nn.functional.avg_pool3d(x, kernel_size, stride=kernel_size)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def apply_rotary_emb_transposed(
|
| 54 |
+
hidden_states: torch.Tensor,
|
| 55 |
+
freqs_cis: torch.Tensor,
|
| 56 |
+
):
|
| 57 |
+
x_1, x_2 = hidden_states.unflatten(-1, (-1, 2)).unbind(-1)
|
| 58 |
+
cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1)
|
| 59 |
+
out = torch.empty_like(hidden_states)
|
| 60 |
+
out[..., 0::2] = x_1 * cos[..., 0::2] - x_2 * sin[..., 1::2]
|
| 61 |
+
out[..., 1::2] = x_1 * sin[..., 1::2] + x_2 * cos[..., 0::2]
|
| 62 |
+
return out.type_as(hidden_states)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _get_qkv_projections(attn: "HeliosAttention", hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor):
|
| 66 |
+
# encoder_hidden_states is only passed for cross-attention
|
| 67 |
+
if encoder_hidden_states is None:
|
| 68 |
+
encoder_hidden_states = hidden_states
|
| 69 |
+
|
| 70 |
+
if attn.fused_projections:
|
| 71 |
+
if not attn.is_cross_attention:
|
| 72 |
+
# In self-attention layers, we can fuse the entire QKV projection into a single linear
|
| 73 |
+
query, key, value = attn.to_qkv(hidden_states).chunk(3, dim=-1)
|
| 74 |
+
else:
|
| 75 |
+
# In cross-attention layers, we can only fuse the KV projections into a single linear
|
| 76 |
+
query = attn.to_q(hidden_states)
|
| 77 |
+
key, value = attn.to_kv(encoder_hidden_states).chunk(2, dim=-1)
|
| 78 |
+
else:
|
| 79 |
+
query = attn.to_q(hidden_states)
|
| 80 |
+
key = attn.to_k(encoder_hidden_states)
|
| 81 |
+
value = attn.to_v(encoder_hidden_states)
|
| 82 |
+
return query, key, value
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class HeliosOutputNorm(nn.Module):
|
| 86 |
+
def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine: bool = False):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.scale_shift_table = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
|
| 89 |
+
self.norm = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 90 |
+
|
| 91 |
+
def forward(self, hidden_states: torch.Tensor, temb: torch.Tensor, original_context_length: int):
|
| 92 |
+
temb = temb[:, -original_context_length:, :]
|
| 93 |
+
shift, scale = (self.scale_shift_table.unsqueeze(0).to(temb.device) + temb.unsqueeze(2)).chunk(2, dim=2)
|
| 94 |
+
shift, scale = shift.squeeze(2).to(hidden_states.device), scale.squeeze(2).to(hidden_states.device)
|
| 95 |
+
hidden_states = hidden_states[:, -original_context_length:, :]
|
| 96 |
+
hidden_states = (self.norm(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
|
| 97 |
+
return hidden_states
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class HeliosAttnProcessor:
|
| 101 |
+
_attention_backend = None
|
| 102 |
+
_parallel_config = None
|
| 103 |
+
|
| 104 |
+
def __init__(self):
|
| 105 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 106 |
+
raise ImportError(
|
| 107 |
+
"HeliosAttnProcessor requires PyTorch 2.0. To use it, please upgrade PyTorch to version 2.0 or higher."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
def __call__(
|
| 111 |
+
self,
|
| 112 |
+
attn: "HeliosAttention",
|
| 113 |
+
hidden_states: torch.Tensor,
|
| 114 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 115 |
+
attention_mask: torch.Tensor | None = None,
|
| 116 |
+
rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 117 |
+
original_context_length: int = None,
|
| 118 |
+
) -> torch.Tensor:
|
| 119 |
+
query, key, value = _get_qkv_projections(attn, hidden_states, encoder_hidden_states)
|
| 120 |
+
|
| 121 |
+
query = attn.norm_q(query)
|
| 122 |
+
key = attn.norm_k(key)
|
| 123 |
+
|
| 124 |
+
query = query.unflatten(2, (attn.heads, -1))
|
| 125 |
+
key = key.unflatten(2, (attn.heads, -1))
|
| 126 |
+
value = value.unflatten(2, (attn.heads, -1))
|
| 127 |
+
|
| 128 |
+
if rotary_emb is not None:
|
| 129 |
+
query = apply_rotary_emb_transposed(query, rotary_emb)
|
| 130 |
+
key = apply_rotary_emb_transposed(key, rotary_emb)
|
| 131 |
+
|
| 132 |
+
if not attn.is_cross_attention and attn.is_amplify_history:
|
| 133 |
+
history_seq_len = hidden_states.shape[1] - original_context_length
|
| 134 |
+
|
| 135 |
+
if history_seq_len > 0:
|
| 136 |
+
scale_key = 1.0 + torch.sigmoid(attn.history_key_scale) * (attn.max_scale - 1.0)
|
| 137 |
+
if attn.history_scale_mode == "per_head":
|
| 138 |
+
scale_key = scale_key.view(1, 1, -1, 1)
|
| 139 |
+
key = torch.cat([key[:, :history_seq_len] * scale_key, key[:, history_seq_len:]], dim=1)
|
| 140 |
+
|
| 141 |
+
hidden_states = dispatch_attention_fn(
|
| 142 |
+
query,
|
| 143 |
+
key,
|
| 144 |
+
value,
|
| 145 |
+
attn_mask=attention_mask,
|
| 146 |
+
dropout_p=0.0,
|
| 147 |
+
is_causal=False,
|
| 148 |
+
backend=self._attention_backend,
|
| 149 |
+
# Reference: https://github.com/huggingface/diffusers/pull/12909
|
| 150 |
+
parallel_config=(self._parallel_config if encoder_hidden_states is None else None),
|
| 151 |
+
)
|
| 152 |
+
hidden_states = hidden_states.flatten(2, 3)
|
| 153 |
+
hidden_states = hidden_states.type_as(query)
|
| 154 |
+
|
| 155 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 156 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 157 |
+
return hidden_states
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class HeliosAttention(torch.nn.Module, AttentionModuleMixin):
|
| 161 |
+
_default_processor_cls = HeliosAttnProcessor
|
| 162 |
+
_available_processors = [HeliosAttnProcessor]
|
| 163 |
+
|
| 164 |
+
def __init__(
|
| 165 |
+
self,
|
| 166 |
+
dim: int,
|
| 167 |
+
heads: int = 8,
|
| 168 |
+
dim_head: int = 64,
|
| 169 |
+
eps: float = 1e-5,
|
| 170 |
+
dropout: float = 0.0,
|
| 171 |
+
added_kv_proj_dim: int | None = None,
|
| 172 |
+
cross_attention_dim_head: int | None = None,
|
| 173 |
+
processor=None,
|
| 174 |
+
is_cross_attention=None,
|
| 175 |
+
is_amplify_history=False,
|
| 176 |
+
history_scale_mode="per_head", # [scalar, per_head]
|
| 177 |
+
):
|
| 178 |
+
super().__init__()
|
| 179 |
+
|
| 180 |
+
self.inner_dim = dim_head * heads
|
| 181 |
+
self.heads = heads
|
| 182 |
+
self.added_kv_proj_dim = added_kv_proj_dim
|
| 183 |
+
self.cross_attention_dim_head = cross_attention_dim_head
|
| 184 |
+
self.kv_inner_dim = self.inner_dim if cross_attention_dim_head is None else cross_attention_dim_head * heads
|
| 185 |
+
|
| 186 |
+
self.to_q = torch.nn.Linear(dim, self.inner_dim, bias=True)
|
| 187 |
+
self.to_k = torch.nn.Linear(dim, self.kv_inner_dim, bias=True)
|
| 188 |
+
self.to_v = torch.nn.Linear(dim, self.kv_inner_dim, bias=True)
|
| 189 |
+
self.to_out = torch.nn.ModuleList(
|
| 190 |
+
[
|
| 191 |
+
torch.nn.Linear(self.inner_dim, dim, bias=True),
|
| 192 |
+
torch.nn.Dropout(dropout),
|
| 193 |
+
]
|
| 194 |
+
)
|
| 195 |
+
self.norm_q = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True)
|
| 196 |
+
self.norm_k = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True)
|
| 197 |
+
|
| 198 |
+
self.add_k_proj = self.add_v_proj = None
|
| 199 |
+
if added_kv_proj_dim is not None:
|
| 200 |
+
self.add_k_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True)
|
| 201 |
+
self.add_v_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True)
|
| 202 |
+
self.norm_added_k = torch.nn.RMSNorm(dim_head * heads, eps=eps)
|
| 203 |
+
|
| 204 |
+
if is_cross_attention is not None:
|
| 205 |
+
self.is_cross_attention = is_cross_attention
|
| 206 |
+
else:
|
| 207 |
+
self.is_cross_attention = cross_attention_dim_head is not None
|
| 208 |
+
|
| 209 |
+
self.set_processor(processor)
|
| 210 |
+
|
| 211 |
+
self.is_amplify_history = is_amplify_history
|
| 212 |
+
if is_amplify_history:
|
| 213 |
+
if history_scale_mode == "scalar":
|
| 214 |
+
self.history_key_scale = nn.Parameter(torch.ones(1))
|
| 215 |
+
elif history_scale_mode == "per_head":
|
| 216 |
+
self.history_key_scale = nn.Parameter(torch.ones(heads))
|
| 217 |
+
else:
|
| 218 |
+
raise ValueError(f"Unknown history_scale_mode: {history_scale_mode}")
|
| 219 |
+
self.history_scale_mode = history_scale_mode
|
| 220 |
+
self.max_scale = 10.0
|
| 221 |
+
|
| 222 |
+
def fuse_projections(self):
|
| 223 |
+
if getattr(self, "fused_projections", False):
|
| 224 |
+
return
|
| 225 |
+
|
| 226 |
+
if not self.is_cross_attention:
|
| 227 |
+
concatenated_weights = torch.cat([self.to_q.weight.data, self.to_k.weight.data, self.to_v.weight.data])
|
| 228 |
+
concatenated_bias = torch.cat([self.to_q.bias.data, self.to_k.bias.data, self.to_v.bias.data])
|
| 229 |
+
out_features, in_features = concatenated_weights.shape
|
| 230 |
+
with torch.device("meta"):
|
| 231 |
+
self.to_qkv = nn.Linear(in_features, out_features, bias=True)
|
| 232 |
+
self.to_qkv.load_state_dict(
|
| 233 |
+
{"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True
|
| 234 |
+
)
|
| 235 |
+
else:
|
| 236 |
+
concatenated_weights = torch.cat([self.to_k.weight.data, self.to_v.weight.data])
|
| 237 |
+
concatenated_bias = torch.cat([self.to_k.bias.data, self.to_v.bias.data])
|
| 238 |
+
out_features, in_features = concatenated_weights.shape
|
| 239 |
+
with torch.device("meta"):
|
| 240 |
+
self.to_kv = nn.Linear(in_features, out_features, bias=True)
|
| 241 |
+
self.to_kv.load_state_dict(
|
| 242 |
+
{"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
if self.added_kv_proj_dim is not None:
|
| 246 |
+
concatenated_weights = torch.cat([self.add_k_proj.weight.data, self.add_v_proj.weight.data])
|
| 247 |
+
concatenated_bias = torch.cat([self.add_k_proj.bias.data, self.add_v_proj.bias.data])
|
| 248 |
+
out_features, in_features = concatenated_weights.shape
|
| 249 |
+
with torch.device("meta"):
|
| 250 |
+
self.to_added_kv = nn.Linear(in_features, out_features, bias=True)
|
| 251 |
+
self.to_added_kv.load_state_dict(
|
| 252 |
+
{"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
self.fused_projections = True
|
| 256 |
+
|
| 257 |
+
@torch.no_grad()
|
| 258 |
+
def unfuse_projections(self):
|
| 259 |
+
if not getattr(self, "fused_projections", False):
|
| 260 |
+
return
|
| 261 |
+
|
| 262 |
+
if hasattr(self, "to_qkv"):
|
| 263 |
+
delattr(self, "to_qkv")
|
| 264 |
+
if hasattr(self, "to_kv"):
|
| 265 |
+
delattr(self, "to_kv")
|
| 266 |
+
if hasattr(self, "to_added_kv"):
|
| 267 |
+
delattr(self, "to_added_kv")
|
| 268 |
+
|
| 269 |
+
self.fused_projections = False
|
| 270 |
+
|
| 271 |
+
def forward(
|
| 272 |
+
self,
|
| 273 |
+
hidden_states: torch.Tensor,
|
| 274 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 275 |
+
attention_mask: torch.Tensor | None = None,
|
| 276 |
+
rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 277 |
+
original_context_length: int = None,
|
| 278 |
+
**kwargs,
|
| 279 |
+
) -> torch.Tensor:
|
| 280 |
+
return self.processor(
|
| 281 |
+
self,
|
| 282 |
+
hidden_states,
|
| 283 |
+
encoder_hidden_states,
|
| 284 |
+
attention_mask,
|
| 285 |
+
rotary_emb,
|
| 286 |
+
original_context_length,
|
| 287 |
+
**kwargs,
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class HeliosTimeTextEmbedding(nn.Module):
|
| 292 |
+
def __init__(
|
| 293 |
+
self,
|
| 294 |
+
dim: int,
|
| 295 |
+
time_freq_dim: int,
|
| 296 |
+
time_proj_dim: int,
|
| 297 |
+
text_embed_dim: int,
|
| 298 |
+
):
|
| 299 |
+
super().__init__()
|
| 300 |
+
|
| 301 |
+
self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
|
| 302 |
+
self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
|
| 303 |
+
self.act_fn = nn.SiLU()
|
| 304 |
+
self.time_proj = nn.Linear(dim, time_proj_dim)
|
| 305 |
+
self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
|
| 306 |
+
|
| 307 |
+
def forward(
|
| 308 |
+
self,
|
| 309 |
+
timestep: torch.Tensor,
|
| 310 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 311 |
+
is_return_encoder_hidden_states: bool = True,
|
| 312 |
+
):
|
| 313 |
+
timestep = self.timesteps_proj(timestep)
|
| 314 |
+
|
| 315 |
+
time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
|
| 316 |
+
if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
|
| 317 |
+
timestep = timestep.to(time_embedder_dtype)
|
| 318 |
+
temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
|
| 319 |
+
timestep_proj = self.time_proj(self.act_fn(temb))
|
| 320 |
+
|
| 321 |
+
if encoder_hidden_states is not None and is_return_encoder_hidden_states:
|
| 322 |
+
encoder_hidden_states = self.text_embedder(encoder_hidden_states)
|
| 323 |
+
|
| 324 |
+
return temb, timestep_proj, encoder_hidden_states
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class HeliosRotaryPosEmbed(nn.Module):
|
| 328 |
+
def __init__(self, rope_dim, theta):
|
| 329 |
+
super().__init__()
|
| 330 |
+
self.DT, self.DY, self.DX = rope_dim
|
| 331 |
+
self.theta = theta
|
| 332 |
+
self.register_buffer("freqs_base_t", self._get_freqs_base(self.DT), persistent=False)
|
| 333 |
+
self.register_buffer("freqs_base_y", self._get_freqs_base(self.DY), persistent=False)
|
| 334 |
+
self.register_buffer("freqs_base_x", self._get_freqs_base(self.DX), persistent=False)
|
| 335 |
+
|
| 336 |
+
def _get_freqs_base(self, dim):
|
| 337 |
+
return 1.0 / (self.theta ** (torch.arange(0, dim, 2, dtype=torch.float32)[: (dim // 2)] / dim))
|
| 338 |
+
|
| 339 |
+
@torch.no_grad()
|
| 340 |
+
def get_frequency_batched(self, freqs_base, pos):
|
| 341 |
+
freqs = torch.einsum("d,bthw->dbthw", freqs_base, pos)
|
| 342 |
+
freqs = freqs.repeat_interleave(2, dim=0)
|
| 343 |
+
return freqs.cos(), freqs.sin()
|
| 344 |
+
|
| 345 |
+
@torch.no_grad()
|
| 346 |
+
@lru_cache(maxsize=32)
|
| 347 |
+
def _get_spatial_meshgrid(self, height, width, device_str):
|
| 348 |
+
device = torch.device(device_str)
|
| 349 |
+
grid_y_coords = torch.arange(height, device=device, dtype=torch.float32)
|
| 350 |
+
grid_x_coords = torch.arange(width, device=device, dtype=torch.float32)
|
| 351 |
+
grid_y, grid_x = torch.meshgrid(grid_y_coords, grid_x_coords, indexing="ij")
|
| 352 |
+
return grid_y, grid_x
|
| 353 |
+
|
| 354 |
+
@torch.no_grad()
|
| 355 |
+
def forward(self, frame_indices, height, width, device):
|
| 356 |
+
batch_size = frame_indices.shape[0]
|
| 357 |
+
num_frames = frame_indices.shape[1]
|
| 358 |
+
|
| 359 |
+
frame_indices = frame_indices.to(device=device, dtype=torch.float32)
|
| 360 |
+
grid_y, grid_x = self._get_spatial_meshgrid(height, width, str(device))
|
| 361 |
+
|
| 362 |
+
grid_t = frame_indices[:, :, None, None].expand(batch_size, num_frames, height, width)
|
| 363 |
+
grid_y_batch = grid_y[None, None, :, :].expand(batch_size, num_frames, -1, -1)
|
| 364 |
+
grid_x_batch = grid_x[None, None, :, :].expand(batch_size, num_frames, -1, -1)
|
| 365 |
+
|
| 366 |
+
freqs_cos_t, freqs_sin_t = self.get_frequency_batched(self.freqs_base_t, grid_t)
|
| 367 |
+
freqs_cos_y, freqs_sin_y = self.get_frequency_batched(self.freqs_base_y, grid_y_batch)
|
| 368 |
+
freqs_cos_x, freqs_sin_x = self.get_frequency_batched(self.freqs_base_x, grid_x_batch)
|
| 369 |
+
|
| 370 |
+
result = torch.cat([freqs_cos_t, freqs_cos_y, freqs_cos_x, freqs_sin_t, freqs_sin_y, freqs_sin_x], dim=0)
|
| 371 |
+
|
| 372 |
+
return result.permute(1, 0, 2, 3, 4)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
@maybe_allow_in_graph
|
| 376 |
+
class HeliosTransformerBlock(nn.Module):
|
| 377 |
+
def __init__(
|
| 378 |
+
self,
|
| 379 |
+
dim: int,
|
| 380 |
+
ffn_dim: int,
|
| 381 |
+
num_heads: int,
|
| 382 |
+
qk_norm: str = "rms_norm_across_heads",
|
| 383 |
+
cross_attn_norm: bool = False,
|
| 384 |
+
eps: float = 1e-6,
|
| 385 |
+
added_kv_proj_dim: int | None = None,
|
| 386 |
+
guidance_cross_attn: bool = False,
|
| 387 |
+
is_amplify_history: bool = False,
|
| 388 |
+
history_scale_mode: str = "per_head", # [scalar, per_head]
|
| 389 |
+
):
|
| 390 |
+
super().__init__()
|
| 391 |
+
|
| 392 |
+
# 1. Self-attention
|
| 393 |
+
self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 394 |
+
self.attn1 = HeliosAttention(
|
| 395 |
+
dim=dim,
|
| 396 |
+
heads=num_heads,
|
| 397 |
+
dim_head=dim // num_heads,
|
| 398 |
+
eps=eps,
|
| 399 |
+
cross_attention_dim_head=None,
|
| 400 |
+
processor=HeliosAttnProcessor(),
|
| 401 |
+
is_amplify_history=is_amplify_history,
|
| 402 |
+
history_scale_mode=history_scale_mode,
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# 2. Cross-attention
|
| 406 |
+
self.attn2 = HeliosAttention(
|
| 407 |
+
dim=dim,
|
| 408 |
+
heads=num_heads,
|
| 409 |
+
dim_head=dim // num_heads,
|
| 410 |
+
eps=eps,
|
| 411 |
+
added_kv_proj_dim=added_kv_proj_dim,
|
| 412 |
+
cross_attention_dim_head=dim // num_heads,
|
| 413 |
+
processor=HeliosAttnProcessor(),
|
| 414 |
+
)
|
| 415 |
+
self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
|
| 416 |
+
|
| 417 |
+
# 3. Feed-forward
|
| 418 |
+
self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
|
| 419 |
+
self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 420 |
+
|
| 421 |
+
self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
|
| 422 |
+
|
| 423 |
+
# 4. Guidance cross-attention
|
| 424 |
+
self.guidance_cross_attn = guidance_cross_attn
|
| 425 |
+
|
| 426 |
+
def forward(
|
| 427 |
+
self,
|
| 428 |
+
hidden_states: torch.Tensor,
|
| 429 |
+
encoder_hidden_states: torch.Tensor,
|
| 430 |
+
temb: torch.Tensor,
|
| 431 |
+
rotary_emb: torch.Tensor,
|
| 432 |
+
original_context_length: int = None,
|
| 433 |
+
) -> torch.Tensor:
|
| 434 |
+
if temb.ndim == 4:
|
| 435 |
+
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
| 436 |
+
self.scale_shift_table.unsqueeze(0) + temb.float()
|
| 437 |
+
).chunk(6, dim=2)
|
| 438 |
+
# batch_size, seq_len, 1, inner_dim
|
| 439 |
+
shift_msa = shift_msa.squeeze(2)
|
| 440 |
+
scale_msa = scale_msa.squeeze(2)
|
| 441 |
+
gate_msa = gate_msa.squeeze(2)
|
| 442 |
+
c_shift_msa = c_shift_msa.squeeze(2)
|
| 443 |
+
c_scale_msa = c_scale_msa.squeeze(2)
|
| 444 |
+
c_gate_msa = c_gate_msa.squeeze(2)
|
| 445 |
+
else:
|
| 446 |
+
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
| 447 |
+
self.scale_shift_table + temb.float()
|
| 448 |
+
).chunk(6, dim=1)
|
| 449 |
+
|
| 450 |
+
# 1. Self-attention
|
| 451 |
+
norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
|
| 452 |
+
attn_output = self.attn1(
|
| 453 |
+
norm_hidden_states,
|
| 454 |
+
None,
|
| 455 |
+
None,
|
| 456 |
+
rotary_emb,
|
| 457 |
+
original_context_length,
|
| 458 |
+
)
|
| 459 |
+
hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
|
| 460 |
+
|
| 461 |
+
# 2. Cross-attention
|
| 462 |
+
if self.guidance_cross_attn:
|
| 463 |
+
history_seq_len = hidden_states.shape[1] - original_context_length
|
| 464 |
+
|
| 465 |
+
history_hidden_states, hidden_states = torch.split(
|
| 466 |
+
hidden_states, [history_seq_len, original_context_length], dim=1
|
| 467 |
+
)
|
| 468 |
+
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
| 469 |
+
attn_output = self.attn2(
|
| 470 |
+
norm_hidden_states,
|
| 471 |
+
encoder_hidden_states,
|
| 472 |
+
None,
|
| 473 |
+
None,
|
| 474 |
+
original_context_length,
|
| 475 |
+
)
|
| 476 |
+
hidden_states = hidden_states + attn_output
|
| 477 |
+
hidden_states = torch.cat([history_hidden_states, hidden_states], dim=1)
|
| 478 |
+
else:
|
| 479 |
+
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
| 480 |
+
attn_output = self.attn2(
|
| 481 |
+
norm_hidden_states,
|
| 482 |
+
encoder_hidden_states,
|
| 483 |
+
None,
|
| 484 |
+
None,
|
| 485 |
+
original_context_length,
|
| 486 |
+
)
|
| 487 |
+
hidden_states = hidden_states + attn_output
|
| 488 |
+
|
| 489 |
+
# 3. Feed-forward
|
| 490 |
+
norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
|
| 491 |
+
hidden_states
|
| 492 |
+
)
|
| 493 |
+
ff_output = self.ffn(norm_hidden_states)
|
| 494 |
+
hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
|
| 495 |
+
|
| 496 |
+
return hidden_states
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
class HeliosTransformer3DModel(
|
| 500 |
+
ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin, AttentionMixin
|
| 501 |
+
):
|
| 502 |
+
r"""
|
| 503 |
+
A Transformer model for video-like data used in the Helios model.
|
| 504 |
+
|
| 505 |
+
Args:
|
| 506 |
+
patch_size (`tuple[int]`, defaults to `(1, 2, 2)`):
|
| 507 |
+
3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
|
| 508 |
+
num_attention_heads (`int`, defaults to `40`):
|
| 509 |
+
Fixed length for text embeddings.
|
| 510 |
+
attention_head_dim (`int`, defaults to `128`):
|
| 511 |
+
The number of channels in each head.
|
| 512 |
+
in_channels (`int`, defaults to `16`):
|
| 513 |
+
The number of channels in the input.
|
| 514 |
+
out_channels (`int`, defaults to `16`):
|
| 515 |
+
The number of channels in the output.
|
| 516 |
+
text_dim (`int`, defaults to `512`):
|
| 517 |
+
Input dimension for text embeddings.
|
| 518 |
+
freq_dim (`int`, defaults to `256`):
|
| 519 |
+
Dimension for sinusoidal time embeddings.
|
| 520 |
+
ffn_dim (`int`, defaults to `13824`):
|
| 521 |
+
Intermediate dimension in feed-forward network.
|
| 522 |
+
num_layers (`int`, defaults to `40`):
|
| 523 |
+
The number of layers of transformer blocks to use.
|
| 524 |
+
window_size (`tuple[int]`, defaults to `(-1, -1)`):
|
| 525 |
+
Window size for local attention (-1 indicates global attention).
|
| 526 |
+
cross_attn_norm (`bool`, defaults to `True`):
|
| 527 |
+
Enable cross-attention normalization.
|
| 528 |
+
qk_norm (`bool`, defaults to `True`):
|
| 529 |
+
Enable query/key normalization.
|
| 530 |
+
eps (`float`, defaults to `1e-6`):
|
| 531 |
+
Epsilon value for normalization layers.
|
| 532 |
+
add_img_emb (`bool`, defaults to `False`):
|
| 533 |
+
Whether to use img_emb.
|
| 534 |
+
added_kv_proj_dim (`int`, *optional*, defaults to `None`):
|
| 535 |
+
The number of channels to use for the added key and value projections. If `None`, no projection is used.
|
| 536 |
+
"""
|
| 537 |
+
|
| 538 |
+
_supports_gradient_checkpointing = True
|
| 539 |
+
_skip_layerwise_casting_patterns = [
|
| 540 |
+
"patch_embedding",
|
| 541 |
+
"patch_short",
|
| 542 |
+
"patch_mid",
|
| 543 |
+
"patch_long",
|
| 544 |
+
"condition_embedder",
|
| 545 |
+
"norm",
|
| 546 |
+
]
|
| 547 |
+
_no_split_modules = ["HeliosTransformerBlock", "HeliosOutputNorm"]
|
| 548 |
+
_keep_in_fp32_modules = [
|
| 549 |
+
"time_embedder",
|
| 550 |
+
"scale_shift_table",
|
| 551 |
+
"norm1",
|
| 552 |
+
"norm2",
|
| 553 |
+
"norm3",
|
| 554 |
+
"history_key_scale",
|
| 555 |
+
]
|
| 556 |
+
_keys_to_ignore_on_load_unexpected = ["norm_added_q"]
|
| 557 |
+
_repeated_blocks = ["HeliosTransformerBlock"]
|
| 558 |
+
_cp_plan = {
|
| 559 |
+
# Input split at attn level and ffn level.
|
| 560 |
+
"blocks.*.attn1": {
|
| 561 |
+
"hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 562 |
+
"rotary_emb": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 563 |
+
},
|
| 564 |
+
"blocks.*.attn2": {
|
| 565 |
+
"hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 566 |
+
},
|
| 567 |
+
"blocks.*.ffn": {
|
| 568 |
+
"hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 569 |
+
},
|
| 570 |
+
# Output gather at attn level and ffn level.
|
| 571 |
+
**{f"blocks.{i}.attn1": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)},
|
| 572 |
+
**{f"blocks.{i}.attn2": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)},
|
| 573 |
+
**{f"blocks.{i}.ffn": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)},
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
@register_to_config
|
| 577 |
+
def __init__(
|
| 578 |
+
self,
|
| 579 |
+
patch_size: tuple[int, ...] = (1, 2, 2),
|
| 580 |
+
num_attention_heads: int = 40,
|
| 581 |
+
attention_head_dim: int = 128,
|
| 582 |
+
in_channels: int = 16,
|
| 583 |
+
out_channels: int = 16,
|
| 584 |
+
text_dim: int = 4096,
|
| 585 |
+
freq_dim: int = 256,
|
| 586 |
+
ffn_dim: int = 13824,
|
| 587 |
+
num_layers: int = 40,
|
| 588 |
+
cross_attn_norm: bool = True,
|
| 589 |
+
qk_norm: str | None = "rms_norm_across_heads",
|
| 590 |
+
eps: float = 1e-6,
|
| 591 |
+
added_kv_proj_dim: int | None = None,
|
| 592 |
+
rope_dim: tuple[int, ...] = (44, 42, 42),
|
| 593 |
+
rope_theta: float = 10000.0,
|
| 594 |
+
guidance_cross_attn: bool = True,
|
| 595 |
+
zero_history_timestep: bool = True,
|
| 596 |
+
has_multi_term_memory_patch: bool = True,
|
| 597 |
+
is_amplify_history: bool = False,
|
| 598 |
+
history_scale_mode: str = "per_head", # [scalar, per_head]
|
| 599 |
+
) -> None:
|
| 600 |
+
super().__init__()
|
| 601 |
+
|
| 602 |
+
inner_dim = num_attention_heads * attention_head_dim
|
| 603 |
+
out_channels = out_channels or in_channels
|
| 604 |
+
|
| 605 |
+
# 1. Patch & position embedding
|
| 606 |
+
self.rope = HeliosRotaryPosEmbed(rope_dim=rope_dim, theta=rope_theta)
|
| 607 |
+
self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
|
| 608 |
+
|
| 609 |
+
# 2. Initial Multi Term Memory Patch
|
| 610 |
+
self.zero_history_timestep = zero_history_timestep
|
| 611 |
+
self.inner_dim = inner_dim
|
| 612 |
+
if has_multi_term_memory_patch:
|
| 613 |
+
self.patch_short = nn.Conv3d(in_channels, self.inner_dim, kernel_size=patch_size, stride=patch_size)
|
| 614 |
+
self.patch_mid = nn.Conv3d(
|
| 615 |
+
in_channels,
|
| 616 |
+
self.inner_dim,
|
| 617 |
+
kernel_size=tuple(2 * p for p in patch_size),
|
| 618 |
+
stride=tuple(2 * p for p in patch_size),
|
| 619 |
+
)
|
| 620 |
+
self.patch_long = nn.Conv3d(
|
| 621 |
+
in_channels,
|
| 622 |
+
self.inner_dim,
|
| 623 |
+
kernel_size=tuple(4 * p for p in patch_size),
|
| 624 |
+
stride=tuple(4 * p for p in patch_size),
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
# 3. Condition embeddings
|
| 628 |
+
self.condition_embedder = HeliosTimeTextEmbedding(
|
| 629 |
+
dim=inner_dim,
|
| 630 |
+
time_freq_dim=freq_dim,
|
| 631 |
+
time_proj_dim=inner_dim * 6,
|
| 632 |
+
text_embed_dim=text_dim,
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
# 4. Transformer blocks
|
| 636 |
+
self.blocks = nn.ModuleList(
|
| 637 |
+
[
|
| 638 |
+
HeliosTransformerBlock(
|
| 639 |
+
inner_dim,
|
| 640 |
+
ffn_dim,
|
| 641 |
+
num_attention_heads,
|
| 642 |
+
qk_norm,
|
| 643 |
+
cross_attn_norm,
|
| 644 |
+
eps,
|
| 645 |
+
added_kv_proj_dim,
|
| 646 |
+
guidance_cross_attn=guidance_cross_attn,
|
| 647 |
+
is_amplify_history=is_amplify_history,
|
| 648 |
+
history_scale_mode=history_scale_mode,
|
| 649 |
+
)
|
| 650 |
+
for _ in range(num_layers)
|
| 651 |
+
]
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
# 5. Output norm & projection
|
| 655 |
+
self.norm_out = HeliosOutputNorm(inner_dim, eps, elementwise_affine=False)
|
| 656 |
+
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
|
| 657 |
+
|
| 658 |
+
self.gradient_checkpointing = False
|
| 659 |
+
|
| 660 |
+
@apply_lora_scale("attention_kwargs")
|
| 661 |
+
def forward(
|
| 662 |
+
self,
|
| 663 |
+
hidden_states: torch.Tensor,
|
| 664 |
+
timestep: torch.LongTensor,
|
| 665 |
+
encoder_hidden_states: torch.Tensor,
|
| 666 |
+
# ------------ Stage 1 ------------
|
| 667 |
+
indices_hidden_states=None,
|
| 668 |
+
indices_latents_history_short=None,
|
| 669 |
+
indices_latents_history_mid=None,
|
| 670 |
+
indices_latents_history_long=None,
|
| 671 |
+
latents_history_short=None,
|
| 672 |
+
latents_history_mid=None,
|
| 673 |
+
latents_history_long=None,
|
| 674 |
+
return_dict: bool = True,
|
| 675 |
+
attention_kwargs: dict[str, Any] | None = None,
|
| 676 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 677 |
+
# 1. Input
|
| 678 |
+
batch_size = hidden_states.shape[0]
|
| 679 |
+
p_t, p_h, p_w = self.config.patch_size
|
| 680 |
+
|
| 681 |
+
# 2. Process noisy latents
|
| 682 |
+
hidden_states = self.patch_embedding(hidden_states)
|
| 683 |
+
_, _, post_patch_num_frames, post_patch_height, post_patch_width = hidden_states.shape
|
| 684 |
+
|
| 685 |
+
if indices_hidden_states is None:
|
| 686 |
+
indices_hidden_states = torch.arange(0, post_patch_num_frames).unsqueeze(0).expand(batch_size, -1)
|
| 687 |
+
|
| 688 |
+
hidden_states = hidden_states.flatten(2).transpose(1, 2)
|
| 689 |
+
rotary_emb = self.rope(
|
| 690 |
+
frame_indices=indices_hidden_states,
|
| 691 |
+
height=post_patch_height,
|
| 692 |
+
width=post_patch_width,
|
| 693 |
+
device=hidden_states.device,
|
| 694 |
+
)
|
| 695 |
+
rotary_emb = rotary_emb.flatten(2).transpose(1, 2)
|
| 696 |
+
original_context_length = hidden_states.shape[1]
|
| 697 |
+
|
| 698 |
+
# 3. Process short history latents
|
| 699 |
+
if latents_history_short is not None and indices_latents_history_short is not None:
|
| 700 |
+
latents_history_short = latents_history_short.to(hidden_states)
|
| 701 |
+
latents_history_short = self.patch_short(latents_history_short)
|
| 702 |
+
_, _, _, H1, W1 = latents_history_short.shape
|
| 703 |
+
latents_history_short = latents_history_short.flatten(2).transpose(1, 2)
|
| 704 |
+
|
| 705 |
+
rotary_emb_history_short = self.rope(
|
| 706 |
+
frame_indices=indices_latents_history_short,
|
| 707 |
+
height=H1,
|
| 708 |
+
width=W1,
|
| 709 |
+
device=latents_history_short.device,
|
| 710 |
+
)
|
| 711 |
+
rotary_emb_history_short = rotary_emb_history_short.flatten(2).transpose(1, 2)
|
| 712 |
+
|
| 713 |
+
hidden_states = torch.cat([latents_history_short, hidden_states], dim=1)
|
| 714 |
+
rotary_emb = torch.cat([rotary_emb_history_short, rotary_emb], dim=1)
|
| 715 |
+
|
| 716 |
+
# 4. Process mid history latents
|
| 717 |
+
if latents_history_mid is not None and indices_latents_history_mid is not None:
|
| 718 |
+
latents_history_mid = latents_history_mid.to(hidden_states)
|
| 719 |
+
latents_history_mid = pad_for_3d_conv(latents_history_mid, (2, 4, 4))
|
| 720 |
+
latents_history_mid = self.patch_mid(latents_history_mid)
|
| 721 |
+
latents_history_mid = latents_history_mid.flatten(2).transpose(1, 2)
|
| 722 |
+
|
| 723 |
+
rotary_emb_history_mid = self.rope(
|
| 724 |
+
frame_indices=indices_latents_history_mid,
|
| 725 |
+
height=H1,
|
| 726 |
+
width=W1,
|
| 727 |
+
device=latents_history_mid.device,
|
| 728 |
+
)
|
| 729 |
+
rotary_emb_history_mid = pad_for_3d_conv(rotary_emb_history_mid, (2, 2, 2))
|
| 730 |
+
rotary_emb_history_mid = center_down_sample_3d(rotary_emb_history_mid, (2, 2, 2))
|
| 731 |
+
rotary_emb_history_mid = rotary_emb_history_mid.flatten(2).transpose(1, 2)
|
| 732 |
+
|
| 733 |
+
hidden_states = torch.cat([latents_history_mid, hidden_states], dim=1)
|
| 734 |
+
rotary_emb = torch.cat([rotary_emb_history_mid, rotary_emb], dim=1)
|
| 735 |
+
|
| 736 |
+
# 5. Process long history latents
|
| 737 |
+
if latents_history_long is not None and indices_latents_history_long is not None:
|
| 738 |
+
latents_history_long = latents_history_long.to(hidden_states)
|
| 739 |
+
latents_history_long = pad_for_3d_conv(latents_history_long, (4, 8, 8))
|
| 740 |
+
latents_history_long = self.patch_long(latents_history_long)
|
| 741 |
+
latents_history_long = latents_history_long.flatten(2).transpose(1, 2)
|
| 742 |
+
|
| 743 |
+
rotary_emb_history_long = self.rope(
|
| 744 |
+
frame_indices=indices_latents_history_long,
|
| 745 |
+
height=H1,
|
| 746 |
+
width=W1,
|
| 747 |
+
device=latents_history_long.device,
|
| 748 |
+
)
|
| 749 |
+
rotary_emb_history_long = pad_for_3d_conv(rotary_emb_history_long, (4, 4, 4))
|
| 750 |
+
rotary_emb_history_long = center_down_sample_3d(rotary_emb_history_long, (4, 4, 4))
|
| 751 |
+
rotary_emb_history_long = rotary_emb_history_long.flatten(2).transpose(1, 2)
|
| 752 |
+
|
| 753 |
+
hidden_states = torch.cat([latents_history_long, hidden_states], dim=1)
|
| 754 |
+
rotary_emb = torch.cat([rotary_emb_history_long, rotary_emb], dim=1)
|
| 755 |
+
|
| 756 |
+
history_context_length = hidden_states.shape[1] - original_context_length
|
| 757 |
+
|
| 758 |
+
if indices_hidden_states is not None and self.zero_history_timestep:
|
| 759 |
+
timestep_t0 = torch.zeros((1), dtype=timestep.dtype, device=timestep.device)
|
| 760 |
+
temb_t0, timestep_proj_t0, _ = self.condition_embedder(
|
| 761 |
+
timestep_t0, encoder_hidden_states, is_return_encoder_hidden_states=False
|
| 762 |
+
)
|
| 763 |
+
temb_t0 = temb_t0.unsqueeze(1).expand(batch_size, history_context_length, -1)
|
| 764 |
+
timestep_proj_t0 = (
|
| 765 |
+
timestep_proj_t0.unflatten(-1, (6, -1))
|
| 766 |
+
.view(1, 6, 1, -1)
|
| 767 |
+
.expand(batch_size, -1, history_context_length, -1)
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
temb, timestep_proj, encoder_hidden_states = self.condition_embedder(timestep, encoder_hidden_states)
|
| 771 |
+
timestep_proj = timestep_proj.unflatten(-1, (6, -1))
|
| 772 |
+
|
| 773 |
+
if indices_hidden_states is not None and not self.zero_history_timestep:
|
| 774 |
+
main_repeat_size = hidden_states.shape[1]
|
| 775 |
+
else:
|
| 776 |
+
main_repeat_size = original_context_length
|
| 777 |
+
temb = temb.view(batch_size, 1, -1).expand(batch_size, main_repeat_size, -1)
|
| 778 |
+
timestep_proj = timestep_proj.view(batch_size, 6, 1, -1).expand(batch_size, 6, main_repeat_size, -1)
|
| 779 |
+
|
| 780 |
+
if indices_hidden_states is not None and self.zero_history_timestep:
|
| 781 |
+
temb = torch.cat([temb_t0, temb], dim=1)
|
| 782 |
+
timestep_proj = torch.cat([timestep_proj_t0, timestep_proj], dim=2)
|
| 783 |
+
|
| 784 |
+
if timestep_proj.ndim == 4:
|
| 785 |
+
timestep_proj = timestep_proj.permute(0, 2, 1, 3)
|
| 786 |
+
|
| 787 |
+
# 6. Transformer blocks
|
| 788 |
+
hidden_states = hidden_states.contiguous()
|
| 789 |
+
encoder_hidden_states = encoder_hidden_states.contiguous()
|
| 790 |
+
rotary_emb = rotary_emb.contiguous()
|
| 791 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
| 792 |
+
for block in self.blocks:
|
| 793 |
+
hidden_states = self._gradient_checkpointing_func(
|
| 794 |
+
block,
|
| 795 |
+
hidden_states,
|
| 796 |
+
encoder_hidden_states,
|
| 797 |
+
timestep_proj,
|
| 798 |
+
rotary_emb,
|
| 799 |
+
original_context_length,
|
| 800 |
+
)
|
| 801 |
+
else:
|
| 802 |
+
for block in self.blocks:
|
| 803 |
+
hidden_states = block(
|
| 804 |
+
hidden_states,
|
| 805 |
+
encoder_hidden_states,
|
| 806 |
+
timestep_proj,
|
| 807 |
+
rotary_emb,
|
| 808 |
+
original_context_length,
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
# 7. Normalization
|
| 812 |
+
hidden_states = self.norm_out(hidden_states, temb, original_context_length)
|
| 813 |
+
hidden_states = self.proj_out(hidden_states)
|
| 814 |
+
|
| 815 |
+
# 8. Unpatchify
|
| 816 |
+
hidden_states = hidden_states.reshape(
|
| 817 |
+
batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
|
| 818 |
+
)
|
| 819 |
+
hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
|
| 820 |
+
output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
| 821 |
+
|
| 822 |
+
if not return_dict:
|
| 823 |
+
return (output,)
|
| 824 |
+
|
| 825 |
+
return Transformer2DModelOutput(sample=output)
|
Helios/_DEV/helios/modules/__init__.py
ADDED
|
File without changes
|
Helios/_DEV/helios/modules/transformer_helios.py
ADDED
|
@@ -0,0 +1,1913 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import glob
|
| 16 |
+
import json
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
from functools import lru_cache
|
| 20 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import einops
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn as nn
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
from einops import rearrange
|
| 27 |
+
|
| 28 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 29 |
+
from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
|
| 30 |
+
from diffusers.models._modeling_parallel import ContextParallelInput, ContextParallelOutput
|
| 31 |
+
from diffusers.models.attention import AttentionMixin, AttentionModuleMixin, FeedForward
|
| 32 |
+
from diffusers.models.cache_utils import CacheMixin
|
| 33 |
+
from diffusers.models.embeddings import (
|
| 34 |
+
PixArtAlphaTextProjection,
|
| 35 |
+
TimestepEmbedding,
|
| 36 |
+
Timesteps,
|
| 37 |
+
)
|
| 38 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 39 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 40 |
+
from diffusers.models.normalization import FP32LayerNorm
|
| 41 |
+
from diffusers.utils import apply_lora_scale, deprecate, logging
|
| 42 |
+
from diffusers.utils.torch_utils import maybe_allow_in_graph
|
| 43 |
+
|
| 44 |
+
from .helios_kernels import attn_varlen_func, create_navit_attention_masks
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def pad_for_3d_conv(x, kernel_size):
|
| 51 |
+
b, c, t, h, w = x.shape
|
| 52 |
+
pt, ph, pw = kernel_size
|
| 53 |
+
pad_t = (pt - (t % pt)) % pt
|
| 54 |
+
pad_h = (ph - (h % ph)) % ph
|
| 55 |
+
pad_w = (pw - (w % pw)) % pw
|
| 56 |
+
return torch.nn.functional.pad(x, (0, pad_w, 0, pad_h, 0, pad_t), mode="replicate")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def center_down_sample_3d(x, kernel_size):
|
| 60 |
+
return torch.nn.functional.avg_pool3d(x, kernel_size, stride=kernel_size)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def apply_rotary_emb_transposed(
|
| 64 |
+
hidden_states: torch.Tensor,
|
| 65 |
+
freqs_cis: torch.Tensor,
|
| 66 |
+
):
|
| 67 |
+
x_1, x_2 = hidden_states.unflatten(-1, (-1, 2)).unbind(-1)
|
| 68 |
+
cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1)
|
| 69 |
+
out = torch.empty_like(hidden_states)
|
| 70 |
+
out[..., 0::2] = x_1 * cos[..., 0::2] - x_2 * sin[..., 1::2]
|
| 71 |
+
out[..., 1::2] = x_1 * sin[..., 1::2] + x_2 * cos[..., 0::2]
|
| 72 |
+
return out.type_as(hidden_states)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _get_qkv_projections(attn: "HeliosAttention", hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor):
|
| 76 |
+
# encoder_hidden_states is only passed for cross-attention
|
| 77 |
+
if encoder_hidden_states is None:
|
| 78 |
+
encoder_hidden_states = hidden_states
|
| 79 |
+
|
| 80 |
+
if attn.fused_projections:
|
| 81 |
+
if not attn.is_cross_attention:
|
| 82 |
+
# In self-attention layers, we can fuse the entire QKV projection into a single linear
|
| 83 |
+
query, key, value = attn.to_qkv(hidden_states).chunk(3, dim=-1)
|
| 84 |
+
else:
|
| 85 |
+
# In cross-attention layers, we can only fuse the KV projections into a single linear
|
| 86 |
+
query = attn.to_q(hidden_states)
|
| 87 |
+
key, value = attn.to_kv(encoder_hidden_states).chunk(2, dim=-1)
|
| 88 |
+
else:
|
| 89 |
+
query = attn.to_q(hidden_states)
|
| 90 |
+
key = attn.to_k(encoder_hidden_states)
|
| 91 |
+
value = attn.to_v(encoder_hidden_states)
|
| 92 |
+
return query, key, value
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class Discriminator3DHead(nn.Module):
|
| 96 |
+
def __init__(self, input_channel, cond_map_dim=768):
|
| 97 |
+
super().__init__()
|
| 98 |
+
|
| 99 |
+
self.head3d = nn.Sequential(
|
| 100 |
+
nn.Conv3d(input_channel, cond_map_dim, 3, stride=(1, 1, 1), padding=(1, 1, 1)), # [31, 8, 8]
|
| 101 |
+
nn.GroupNorm(32, cond_map_dim),
|
| 102 |
+
nn.SiLU(False),
|
| 103 |
+
nn.Conv3d(cond_map_dim, cond_map_dim, 4, stride=[2, 2, 2], padding=(1, 1, 1)), # [15, 4, 4]
|
| 104 |
+
nn.GroupNorm(32, cond_map_dim),
|
| 105 |
+
nn.SiLU(False),
|
| 106 |
+
nn.Conv3d(cond_map_dim, cond_map_dim, 4, stride=[2, 2, 2], padding=(1, 1, 1)), # [7, 2, 2]
|
| 107 |
+
nn.GroupNorm(32, cond_map_dim),
|
| 108 |
+
nn.SiLU(False),
|
| 109 |
+
nn.Conv3d(cond_map_dim, cond_map_dim, 3, stride=[2, 1, 1], padding=(1, 1, 1)), # [3, 2, 2]
|
| 110 |
+
nn.GroupNorm(32, cond_map_dim),
|
| 111 |
+
nn.SiLU(False),
|
| 112 |
+
nn.Conv3d(cond_map_dim, cond_map_dim, 3, stride=[2, 1, 1], padding=(1, 1, 1)), # [1, 2, 2]
|
| 113 |
+
nn.GroupNorm(32, cond_map_dim),
|
| 114 |
+
nn.SiLU(False),
|
| 115 |
+
nn.Conv3d(
|
| 116 |
+
cond_map_dim, cond_map_dim, kernel_size=[1, 3, 3], stride=[1, 1, 1], padding=(0, 1, 1)
|
| 117 |
+
), # [b, 768, 1, 1, 2]
|
| 118 |
+
nn.GroupNorm(32, cond_map_dim),
|
| 119 |
+
nn.SiLU(False),
|
| 120 |
+
nn.AdaptiveAvgPool3d((1, 1, 1)),
|
| 121 |
+
nn.Flatten(),
|
| 122 |
+
nn.Linear(cond_map_dim, 1),
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def forward(self, x):
|
| 126 |
+
return self.head3d(x)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class LoRALinearLayer(nn.Module):
|
| 130 |
+
def __init__(
|
| 131 |
+
self,
|
| 132 |
+
in_features: int,
|
| 133 |
+
out_features: int,
|
| 134 |
+
rank: int = 128,
|
| 135 |
+
device="cuda",
|
| 136 |
+
dtype: Optional[torch.dtype] = torch.float32,
|
| 137 |
+
):
|
| 138 |
+
super().__init__()
|
| 139 |
+
self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype)
|
| 140 |
+
self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype)
|
| 141 |
+
self.rank = rank
|
| 142 |
+
self.out_features = out_features
|
| 143 |
+
self.in_features = in_features
|
| 144 |
+
|
| 145 |
+
nn.init.normal_(self.down.weight, std=1 / rank)
|
| 146 |
+
nn.init.zeros_(self.up.weight)
|
| 147 |
+
|
| 148 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 149 |
+
orig_dtype = hidden_states.dtype
|
| 150 |
+
dtype = self.down.weight.dtype
|
| 151 |
+
|
| 152 |
+
down_hidden_states = self.down(hidden_states.to(dtype))
|
| 153 |
+
up_hidden_states = self.up(down_hidden_states)
|
| 154 |
+
return up_hidden_states.to(orig_dtype)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class HeliosOutputNorm(nn.Module):
|
| 158 |
+
def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine: bool = False):
|
| 159 |
+
super().__init__()
|
| 160 |
+
self.scale_shift_table = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
|
| 161 |
+
self.norm = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 162 |
+
|
| 163 |
+
def forward(self, hidden_states: torch.Tensor, temb: torch.Tensor, original_context_length: int):
|
| 164 |
+
temb = temb[:, -original_context_length:, :]
|
| 165 |
+
shift, scale = (self.scale_shift_table.unsqueeze(0).to(temb.device) + temb.unsqueeze(2)).chunk(2, dim=2)
|
| 166 |
+
shift, scale = shift.squeeze(2).to(hidden_states.device), scale.squeeze(2).to(hidden_states.device)
|
| 167 |
+
hidden_states = hidden_states[:, -original_context_length:, :]
|
| 168 |
+
hidden_states = (self.norm(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
|
| 169 |
+
return hidden_states
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class HeliosAttnProcessor:
|
| 173 |
+
_attention_backend = None
|
| 174 |
+
_parallel_config = None
|
| 175 |
+
|
| 176 |
+
def __init__(self):
|
| 177 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 178 |
+
raise ImportError(
|
| 179 |
+
"HeliosAttnProcessor requires PyTorch 2.0. To use it, please upgrade PyTorch to version 2.0 or higher."
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
self.kv_cache = None
|
| 183 |
+
self.cache_enabled = False
|
| 184 |
+
|
| 185 |
+
def enable_cache(self):
|
| 186 |
+
self.cache_enabled = True
|
| 187 |
+
self.kv_cache = None
|
| 188 |
+
|
| 189 |
+
def disable_cache(self):
|
| 190 |
+
self.cache_enabled = False
|
| 191 |
+
self.kv_cache = None
|
| 192 |
+
|
| 193 |
+
def clear_cache(self):
|
| 194 |
+
self.kv_cache = None
|
| 195 |
+
|
| 196 |
+
def __call__(
|
| 197 |
+
self,
|
| 198 |
+
attn: "HeliosAttention",
|
| 199 |
+
hidden_states: torch.Tensor,
|
| 200 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 201 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 202 |
+
rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 203 |
+
original_context_length: int = None,
|
| 204 |
+
original_context_length_list: list = None,
|
| 205 |
+
enable_navit: bool = False,
|
| 206 |
+
is_first_denoising_step: bool = False,
|
| 207 |
+
) -> torch.Tensor:
|
| 208 |
+
use_cache = False
|
| 209 |
+
history_seq_len = None
|
| 210 |
+
enable_cross = attn.is_cross_attention
|
| 211 |
+
|
| 212 |
+
if not enable_cross:
|
| 213 |
+
history_seq_len = (hidden_states.shape[1] - original_context_length) // len(original_context_length_list)
|
| 214 |
+
|
| 215 |
+
if attn.restrict_self_attn:
|
| 216 |
+
use_cache = self.cache_enabled and not is_first_denoising_step and self.kv_cache is not None
|
| 217 |
+
assert not (use_cache and enable_navit), "Cache and NAViT are incompatible"
|
| 218 |
+
|
| 219 |
+
if use_cache:
|
| 220 |
+
key_history = self.kv_cache["key_history"]
|
| 221 |
+
value_history = self.kv_cache["value_history"]
|
| 222 |
+
history_hidden_states = self.kv_cache["history_hidden_states"]
|
| 223 |
+
|
| 224 |
+
hidden_states = hidden_states[:, history_seq_len:]
|
| 225 |
+
rotary_emb = rotary_emb[:, history_seq_len:] if rotary_emb is not None else None
|
| 226 |
+
|
| 227 |
+
query, key, value = _get_qkv_projections(attn, hidden_states, encoder_hidden_states)
|
| 228 |
+
|
| 229 |
+
query = attn.norm_q(query)
|
| 230 |
+
key = attn.norm_k(key)
|
| 231 |
+
|
| 232 |
+
if attn.restrict_self_attn and not use_cache:
|
| 233 |
+
if enable_navit:
|
| 234 |
+
seq_start = 0
|
| 235 |
+
num_seqs = len(original_context_length_list)
|
| 236 |
+
query_list = [None] * num_seqs
|
| 237 |
+
key_list = [None] * num_seqs
|
| 238 |
+
value_list = [None] * num_seqs
|
| 239 |
+
query_history_list = [None] * num_seqs
|
| 240 |
+
key_history_list = [None] * num_seqs
|
| 241 |
+
value_history_list = [None] * num_seqs
|
| 242 |
+
|
| 243 |
+
if attn.restrict_lora:
|
| 244 |
+
history_hidden_states_list = [None] * num_seqs
|
| 245 |
+
|
| 246 |
+
if rotary_emb is not None:
|
| 247 |
+
rotary_emb_list = [None] * num_seqs
|
| 248 |
+
history_rotary_emb_list = [None] * num_seqs
|
| 249 |
+
|
| 250 |
+
for idx, cur_seq_len in enumerate(original_context_length_list[::-1]):
|
| 251 |
+
seq_end = seq_start + cur_seq_len + history_seq_len
|
| 252 |
+
|
| 253 |
+
slice_qkv = slice(seq_start, seq_end)
|
| 254 |
+
cur_query = query[:, slice_qkv, :]
|
| 255 |
+
cur_key = key[:, slice_qkv, :]
|
| 256 |
+
cur_value = value[:, slice_qkv, :]
|
| 257 |
+
|
| 258 |
+
query_history_list[idx] = cur_query[:, :history_seq_len]
|
| 259 |
+
query_list[idx] = cur_query[:, history_seq_len:]
|
| 260 |
+
|
| 261 |
+
key_history_list[idx] = cur_key[:, :history_seq_len]
|
| 262 |
+
key_list[idx] = cur_key[:, history_seq_len:]
|
| 263 |
+
|
| 264 |
+
value_history_list[idx] = cur_value[:, :history_seq_len]
|
| 265 |
+
value_list[idx] = cur_value[:, history_seq_len:]
|
| 266 |
+
|
| 267 |
+
if attn.restrict_lora:
|
| 268 |
+
cur_hidden = hidden_states[:, slice_qkv, :]
|
| 269 |
+
history_hidden_states_list[idx] = cur_hidden[:, :history_seq_len]
|
| 270 |
+
|
| 271 |
+
if rotary_emb is not None:
|
| 272 |
+
cur_rotary_emb = rotary_emb[:, slice_qkv, :]
|
| 273 |
+
history_rotary_emb_list[idx] = cur_rotary_emb[:, :history_seq_len]
|
| 274 |
+
rotary_emb_list[idx] = cur_rotary_emb[:, history_seq_len:]
|
| 275 |
+
|
| 276 |
+
seq_start = seq_end
|
| 277 |
+
|
| 278 |
+
query = torch.cat(query_list, dim=1)
|
| 279 |
+
key = torch.cat(key_list, dim=1)
|
| 280 |
+
value = torch.cat(value_list, dim=1)
|
| 281 |
+
query_history = torch.cat(query_history_list, dim=1)
|
| 282 |
+
key_history = torch.cat(key_history_list, dim=1)
|
| 283 |
+
value_history = torch.cat(value_history_list, dim=1)
|
| 284 |
+
|
| 285 |
+
if attn.restrict_lora:
|
| 286 |
+
history_hidden_states = torch.cat(history_hidden_states_list, dim=1)
|
| 287 |
+
query_history = query_history + attn.q_loras(history_hidden_states)
|
| 288 |
+
key_history = key_history + attn.k_loras(history_hidden_states)
|
| 289 |
+
value_history = value_history + attn.v_loras(history_hidden_states)
|
| 290 |
+
|
| 291 |
+
query_history = query_history.unflatten(2, (attn.heads, -1))
|
| 292 |
+
key_history = key_history.unflatten(2, (attn.heads, -1))
|
| 293 |
+
value_history = value_history.unflatten(2, (attn.heads, -1))
|
| 294 |
+
|
| 295 |
+
if rotary_emb is not None:
|
| 296 |
+
rotary_emb = torch.cat(rotary_emb_list, dim=1)
|
| 297 |
+
history_rotary_emb = torch.cat(history_rotary_emb_list, dim=1)
|
| 298 |
+
query_history = apply_rotary_emb_transposed(query_history, history_rotary_emb)
|
| 299 |
+
key_history = apply_rotary_emb_transposed(key_history, history_rotary_emb)
|
| 300 |
+
else:
|
| 301 |
+
history_hidden_states = hidden_states[:, :history_seq_len]
|
| 302 |
+
query_history, query = query[:, :history_seq_len], query[:, history_seq_len:]
|
| 303 |
+
key_history, key = key[:, :history_seq_len], key[:, history_seq_len:]
|
| 304 |
+
value_history, value = value[:, :history_seq_len], value[:, history_seq_len:]
|
| 305 |
+
|
| 306 |
+
if attn.restrict_lora:
|
| 307 |
+
query_history = query_history + attn.q_loras(history_hidden_states)
|
| 308 |
+
key_history = key_history + attn.k_loras(history_hidden_states)
|
| 309 |
+
value_history = value_history + attn.v_loras(history_hidden_states)
|
| 310 |
+
|
| 311 |
+
query_history = query_history.unflatten(2, (attn.heads, -1))
|
| 312 |
+
key_history = key_history.unflatten(2, (attn.heads, -1))
|
| 313 |
+
value_history = value_history.unflatten(2, (attn.heads, -1))
|
| 314 |
+
|
| 315 |
+
if rotary_emb is not None:
|
| 316 |
+
history_rotary_emb, rotary_emb = (rotary_emb[:, :history_seq_len], rotary_emb[:, history_seq_len:])
|
| 317 |
+
query_history = apply_rotary_emb_transposed(query_history, history_rotary_emb)
|
| 318 |
+
key_history = apply_rotary_emb_transposed(key_history, history_rotary_emb)
|
| 319 |
+
|
| 320 |
+
query = query.unflatten(2, (attn.heads, -1))
|
| 321 |
+
key = key.unflatten(2, (attn.heads, -1))
|
| 322 |
+
value = value.unflatten(2, (attn.heads, -1))
|
| 323 |
+
|
| 324 |
+
if rotary_emb is not None:
|
| 325 |
+
query = apply_rotary_emb_transposed(query, rotary_emb)
|
| 326 |
+
key = apply_rotary_emb_transposed(key, rotary_emb)
|
| 327 |
+
|
| 328 |
+
if attn.restrict_self_attn:
|
| 329 |
+
if use_cache:
|
| 330 |
+
key = torch.cat([key_history, key], dim=1)
|
| 331 |
+
value = torch.cat([value_history, value], dim=1)
|
| 332 |
+
else:
|
| 333 |
+
if enable_navit:
|
| 334 |
+
num_seqs = len(original_context_length_list)
|
| 335 |
+
|
| 336 |
+
key_list = [None] * num_seqs
|
| 337 |
+
value_list = [None] * num_seqs
|
| 338 |
+
|
| 339 |
+
seq_start = 0
|
| 340 |
+
seq_start_history = 0
|
| 341 |
+
|
| 342 |
+
for idx, cur_seq_len in enumerate(original_context_length_list[::-1]):
|
| 343 |
+
key_list[idx] = torch.cat(
|
| 344 |
+
[
|
| 345 |
+
key_history[:, seq_start_history : seq_start_history + history_seq_len, :],
|
| 346 |
+
key[:, seq_start : seq_start + cur_seq_len, :],
|
| 347 |
+
],
|
| 348 |
+
dim=1,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
value_list[idx] = torch.cat(
|
| 352 |
+
[
|
| 353 |
+
value_history[:, seq_start_history : seq_start_history + history_seq_len, :],
|
| 354 |
+
value[:, seq_start : seq_start + cur_seq_len, :],
|
| 355 |
+
],
|
| 356 |
+
dim=1,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
seq_start += cur_seq_len
|
| 360 |
+
seq_start_history += history_seq_len
|
| 361 |
+
|
| 362 |
+
key = torch.cat(key_list, dim=1)
|
| 363 |
+
value = torch.cat(value_list, dim=1)
|
| 364 |
+
|
| 365 |
+
history_hidden_states = attn_varlen_func(
|
| 366 |
+
query_history,
|
| 367 |
+
key_history,
|
| 368 |
+
value_history,
|
| 369 |
+
attention_mask=attention_mask[1],
|
| 370 |
+
)
|
| 371 |
+
else:
|
| 372 |
+
key = torch.cat([key_history, key], dim=1)
|
| 373 |
+
value = torch.cat([value_history, value], dim=1)
|
| 374 |
+
|
| 375 |
+
history_hidden_states = attn_varlen_func(
|
| 376 |
+
query_history,
|
| 377 |
+
key_history,
|
| 378 |
+
value_history,
|
| 379 |
+
)
|
| 380 |
+
history_hidden_states = history_hidden_states.flatten(2, 3)
|
| 381 |
+
history_hidden_states = history_hidden_states.type_as(query)
|
| 382 |
+
|
| 383 |
+
if self.cache_enabled and is_first_denoising_step and not enable_navit:
|
| 384 |
+
self.kv_cache = {
|
| 385 |
+
"key_history": key_history,
|
| 386 |
+
"value_history": value_history,
|
| 387 |
+
"history_hidden_states": history_hidden_states,
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
if enable_cross and enable_navit:
|
| 391 |
+
key = key.repeat(1, len(original_context_length_list), 1, 1)
|
| 392 |
+
value = value.repeat(1, len(original_context_length_list), 1, 1)
|
| 393 |
+
|
| 394 |
+
if not enable_cross and history_seq_len > 0 and attn.is_amplify_history:
|
| 395 |
+
scale_key = attn.get_scale_key()
|
| 396 |
+
if attn.history_scale_mode == "per_head":
|
| 397 |
+
scale_key = scale_key.view(1, 1, -1, 1)
|
| 398 |
+
|
| 399 |
+
if enable_navit:
|
| 400 |
+
key_new = key.clone()
|
| 401 |
+
seq_start = 0
|
| 402 |
+
for cur_seq_len in original_context_length_list[::-1]:
|
| 403 |
+
hist_slice = slice(seq_start, seq_start + history_seq_len)
|
| 404 |
+
key_new[:, hist_slice] = key[:, hist_slice] * scale_key
|
| 405 |
+
seq_start += history_seq_len + cur_seq_len
|
| 406 |
+
key = key_new
|
| 407 |
+
else:
|
| 408 |
+
key = torch.cat([key[:, :history_seq_len] * scale_key, key[:, history_seq_len:]], dim=1)
|
| 409 |
+
|
| 410 |
+
hidden_states = attn_varlen_func(
|
| 411 |
+
query,
|
| 412 |
+
key,
|
| 413 |
+
value,
|
| 414 |
+
attention_mask=attention_mask[0] if isinstance(attention_mask, list) else attention_mask,
|
| 415 |
+
)
|
| 416 |
+
hidden_states = hidden_states.flatten(2, 3)
|
| 417 |
+
hidden_states = hidden_states.type_as(query)
|
| 418 |
+
|
| 419 |
+
if attn.restrict_self_attn:
|
| 420 |
+
if enable_navit:
|
| 421 |
+
num_seqs = len(original_context_length_list)
|
| 422 |
+
hidden_states_list = [None] * num_seqs
|
| 423 |
+
|
| 424 |
+
seq_start = 0
|
| 425 |
+
seq_start_history = 0
|
| 426 |
+
|
| 427 |
+
for idx, cur_seq_len in enumerate(original_context_length_list[::-1]):
|
| 428 |
+
hidden_states_list[idx] = torch.cat(
|
| 429 |
+
[
|
| 430 |
+
history_hidden_states[:, seq_start_history : seq_start_history + history_seq_len, :],
|
| 431 |
+
hidden_states[:, seq_start : seq_start + cur_seq_len, :],
|
| 432 |
+
],
|
| 433 |
+
dim=1,
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
seq_start += cur_seq_len
|
| 437 |
+
seq_start_history += history_seq_len
|
| 438 |
+
|
| 439 |
+
hidden_states = torch.cat(hidden_states_list, dim=1)
|
| 440 |
+
else:
|
| 441 |
+
hidden_states = torch.cat([history_hidden_states, hidden_states], dim=1)
|
| 442 |
+
|
| 443 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 444 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 445 |
+
return hidden_states
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
class HeliosAttnProcessor2_0:
|
| 449 |
+
def __new__(cls, *args, **kwargs):
|
| 450 |
+
deprecation_message = (
|
| 451 |
+
"The HeliosAttnProcessor2_0 class is deprecated and will be removed in a future version. "
|
| 452 |
+
"Please use HeliosAttnProcessor instead. "
|
| 453 |
+
)
|
| 454 |
+
deprecate("HeliosAttnProcessor2_0", "1.0.0", deprecation_message, standard_warn=False)
|
| 455 |
+
return HeliosAttnProcessor(*args, **kwargs)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class HeliosAttention(torch.nn.Module, AttentionModuleMixin):
|
| 459 |
+
_default_processor_cls = HeliosAttnProcessor
|
| 460 |
+
_available_processors = [HeliosAttnProcessor]
|
| 461 |
+
|
| 462 |
+
def __init__(
|
| 463 |
+
self,
|
| 464 |
+
dim: int,
|
| 465 |
+
heads: int = 8,
|
| 466 |
+
dim_head: int = 64,
|
| 467 |
+
eps: float = 1e-5,
|
| 468 |
+
dropout: float = 0.0,
|
| 469 |
+
added_kv_proj_dim: Optional[int] = None,
|
| 470 |
+
cross_attention_dim_head: Optional[int] = None,
|
| 471 |
+
processor=None,
|
| 472 |
+
is_cross_attention=None,
|
| 473 |
+
restrict_self_attn=False,
|
| 474 |
+
is_train_restrict_lora=False,
|
| 475 |
+
restrict_lora=False,
|
| 476 |
+
restrict_lora_rank=128,
|
| 477 |
+
is_amplify_history=False,
|
| 478 |
+
history_scale_mode="per_head", # [scalar, per_head]
|
| 479 |
+
):
|
| 480 |
+
super().__init__()
|
| 481 |
+
|
| 482 |
+
self.inner_dim = dim_head * heads
|
| 483 |
+
self.heads = heads
|
| 484 |
+
self.added_kv_proj_dim = added_kv_proj_dim
|
| 485 |
+
self.cross_attention_dim_head = cross_attention_dim_head
|
| 486 |
+
self.kv_inner_dim = self.inner_dim if cross_attention_dim_head is None else cross_attention_dim_head * heads
|
| 487 |
+
|
| 488 |
+
self.to_q = torch.nn.Linear(dim, self.inner_dim, bias=True)
|
| 489 |
+
self.to_k = torch.nn.Linear(dim, self.kv_inner_dim, bias=True)
|
| 490 |
+
self.to_v = torch.nn.Linear(dim, self.kv_inner_dim, bias=True)
|
| 491 |
+
self.to_out = torch.nn.ModuleList(
|
| 492 |
+
[
|
| 493 |
+
torch.nn.Linear(self.inner_dim, dim, bias=True),
|
| 494 |
+
torch.nn.Dropout(dropout),
|
| 495 |
+
]
|
| 496 |
+
)
|
| 497 |
+
self.norm_q = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True)
|
| 498 |
+
self.norm_k = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True)
|
| 499 |
+
|
| 500 |
+
self.add_k_proj = self.add_v_proj = None
|
| 501 |
+
if added_kv_proj_dim is not None:
|
| 502 |
+
self.add_k_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True)
|
| 503 |
+
self.add_v_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True)
|
| 504 |
+
self.norm_added_k = torch.nn.RMSNorm(dim_head * heads, eps=eps)
|
| 505 |
+
|
| 506 |
+
if is_cross_attention is not None:
|
| 507 |
+
self.is_cross_attention = is_cross_attention
|
| 508 |
+
else:
|
| 509 |
+
self.is_cross_attention = cross_attention_dim_head is not None
|
| 510 |
+
|
| 511 |
+
self.set_processor(processor)
|
| 512 |
+
|
| 513 |
+
self.restrict_self_attn = restrict_self_attn
|
| 514 |
+
self.restrict_lora = restrict_lora
|
| 515 |
+
if restrict_lora:
|
| 516 |
+
self.init_lora(is_train=is_train_restrict_lora, lora_rank=restrict_lora_rank)
|
| 517 |
+
|
| 518 |
+
self.is_amplify_history = is_amplify_history
|
| 519 |
+
if is_amplify_history:
|
| 520 |
+
if history_scale_mode == "scalar":
|
| 521 |
+
self.history_key_scale = nn.Parameter(torch.ones(1))
|
| 522 |
+
elif history_scale_mode == "per_head":
|
| 523 |
+
self.history_key_scale = nn.Parameter(torch.ones(heads))
|
| 524 |
+
else:
|
| 525 |
+
raise ValueError(f"Unknown history_scale_mode: {history_scale_mode}")
|
| 526 |
+
self.history_scale_mode = history_scale_mode
|
| 527 |
+
self.max_scale = 10.0
|
| 528 |
+
self.register_buffer("_scale_cache", None)
|
| 529 |
+
|
| 530 |
+
def get_scale_key(self):
|
| 531 |
+
if self.history_key_scale.requires_grad:
|
| 532 |
+
scale = 1.0 + torch.sigmoid(self.history_key_scale) * (self.max_scale - 1.0)
|
| 533 |
+
else:
|
| 534 |
+
if self._scale_cache is None:
|
| 535 |
+
self._scale_cache = 1.0 + torch.sigmoid(self.history_key_scale) * (self.max_scale - 1.0)
|
| 536 |
+
scale = self._scale_cache
|
| 537 |
+
return scale
|
| 538 |
+
|
| 539 |
+
def init_lora(self, is_train=False, lora_rank=128):
|
| 540 |
+
dim = self.inner_dim
|
| 541 |
+
self.q_loras = LoRALinearLayer(dim, dim, rank=lora_rank)
|
| 542 |
+
self.k_loras = LoRALinearLayer(dim, dim, rank=lora_rank)
|
| 543 |
+
self.v_loras = LoRALinearLayer(dim, dim, rank=lora_rank)
|
| 544 |
+
|
| 545 |
+
requires_grad = is_train
|
| 546 |
+
for lora in [self.q_loras, self.k_loras, self.v_loras]:
|
| 547 |
+
for param in lora.parameters():
|
| 548 |
+
param.requires_grad = requires_grad
|
| 549 |
+
|
| 550 |
+
def fuse_projections(self):
|
| 551 |
+
if getattr(self, "fused_projections", False):
|
| 552 |
+
return
|
| 553 |
+
|
| 554 |
+
if not self.is_cross_attention:
|
| 555 |
+
concatenated_weights = torch.cat([self.to_q.weight.data, self.to_k.weight.data, self.to_v.weight.data])
|
| 556 |
+
concatenated_bias = torch.cat([self.to_q.bias.data, self.to_k.bias.data, self.to_v.bias.data])
|
| 557 |
+
out_features, in_features = concatenated_weights.shape
|
| 558 |
+
with torch.device("meta"):
|
| 559 |
+
self.to_qkv = nn.Linear(in_features, out_features, bias=True)
|
| 560 |
+
self.to_qkv.load_state_dict(
|
| 561 |
+
{"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True
|
| 562 |
+
)
|
| 563 |
+
else:
|
| 564 |
+
concatenated_weights = torch.cat([self.to_k.weight.data, self.to_v.weight.data])
|
| 565 |
+
concatenated_bias = torch.cat([self.to_k.bias.data, self.to_v.bias.data])
|
| 566 |
+
out_features, in_features = concatenated_weights.shape
|
| 567 |
+
with torch.device("meta"):
|
| 568 |
+
self.to_kv = nn.Linear(in_features, out_features, bias=True)
|
| 569 |
+
self.to_kv.load_state_dict(
|
| 570 |
+
{"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
if self.added_kv_proj_dim is not None:
|
| 574 |
+
concatenated_weights = torch.cat([self.add_k_proj.weight.data, self.add_v_proj.weight.data])
|
| 575 |
+
concatenated_bias = torch.cat([self.add_k_proj.bias.data, self.add_v_proj.bias.data])
|
| 576 |
+
out_features, in_features = concatenated_weights.shape
|
| 577 |
+
with torch.device("meta"):
|
| 578 |
+
self.to_added_kv = nn.Linear(in_features, out_features, bias=True)
|
| 579 |
+
self.to_added_kv.load_state_dict(
|
| 580 |
+
{"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
self.fused_projections = True
|
| 584 |
+
|
| 585 |
+
@torch.no_grad()
|
| 586 |
+
def unfuse_projections(self):
|
| 587 |
+
if not getattr(self, "fused_projections", False):
|
| 588 |
+
return
|
| 589 |
+
|
| 590 |
+
if hasattr(self, "to_qkv"):
|
| 591 |
+
delattr(self, "to_qkv")
|
| 592 |
+
if hasattr(self, "to_kv"):
|
| 593 |
+
delattr(self, "to_kv")
|
| 594 |
+
if hasattr(self, "to_added_kv"):
|
| 595 |
+
delattr(self, "to_added_kv")
|
| 596 |
+
|
| 597 |
+
self.fused_projections = False
|
| 598 |
+
|
| 599 |
+
def forward(
|
| 600 |
+
self,
|
| 601 |
+
hidden_states: torch.Tensor,
|
| 602 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 603 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 604 |
+
rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 605 |
+
original_context_length: int = None,
|
| 606 |
+
original_context_length_list: list = None,
|
| 607 |
+
enable_navit: bool = False,
|
| 608 |
+
**kwargs,
|
| 609 |
+
) -> torch.Tensor:
|
| 610 |
+
return self.processor(
|
| 611 |
+
self,
|
| 612 |
+
hidden_states,
|
| 613 |
+
encoder_hidden_states,
|
| 614 |
+
attention_mask,
|
| 615 |
+
rotary_emb,
|
| 616 |
+
original_context_length,
|
| 617 |
+
original_context_length_list,
|
| 618 |
+
enable_navit,
|
| 619 |
+
**kwargs,
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
class HeliosTimeTextEmbedding(nn.Module):
|
| 624 |
+
def __init__(
|
| 625 |
+
self,
|
| 626 |
+
dim: int,
|
| 627 |
+
time_freq_dim: int,
|
| 628 |
+
time_proj_dim: int,
|
| 629 |
+
text_embed_dim: int,
|
| 630 |
+
):
|
| 631 |
+
super().__init__()
|
| 632 |
+
|
| 633 |
+
self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
|
| 634 |
+
self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
|
| 635 |
+
self.act_fn = nn.SiLU()
|
| 636 |
+
self.time_proj = nn.Linear(dim, time_proj_dim)
|
| 637 |
+
self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
|
| 638 |
+
|
| 639 |
+
def forward(
|
| 640 |
+
self,
|
| 641 |
+
timestep: torch.Tensor,
|
| 642 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 643 |
+
is_return_encoder_hidden_states: bool = True,
|
| 644 |
+
):
|
| 645 |
+
B = None
|
| 646 |
+
F = None
|
| 647 |
+
if timestep.ndim == 2:
|
| 648 |
+
B, F = timestep.shape
|
| 649 |
+
timestep = timestep.flatten()
|
| 650 |
+
|
| 651 |
+
timestep = self.timesteps_proj(timestep) # torch.Size([2]) -> torch.Size([2, 256])
|
| 652 |
+
|
| 653 |
+
time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
|
| 654 |
+
if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
|
| 655 |
+
timestep = timestep.to(time_embedder_dtype)
|
| 656 |
+
temb = self.time_embedder(timestep).type_as(encoder_hidden_states) # torch.Size([2, 1536])
|
| 657 |
+
timestep_proj = self.time_proj(self.act_fn(temb)) # torch.Size([2, 9216]
|
| 658 |
+
|
| 659 |
+
if B is not None and F is not None:
|
| 660 |
+
temb = temb.reshape(B, F, -1)
|
| 661 |
+
timestep_proj = timestep_proj.reshape(B, F, -1)
|
| 662 |
+
|
| 663 |
+
if encoder_hidden_states is not None and is_return_encoder_hidden_states:
|
| 664 |
+
encoder_hidden_states = self.text_embedder(encoder_hidden_states) # torch.Size([2, 512, 1536])
|
| 665 |
+
|
| 666 |
+
return temb, timestep_proj, encoder_hidden_states
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
class HeliosRotaryPosEmbed(nn.Module):
|
| 670 |
+
def __init__(self, rope_dim, theta):
|
| 671 |
+
super().__init__()
|
| 672 |
+
self.DT, self.DY, self.DX = rope_dim
|
| 673 |
+
self.theta = theta
|
| 674 |
+
self.register_buffer("freqs_base_t", self._get_freqs_base(self.DT), persistent=False)
|
| 675 |
+
self.register_buffer("freqs_base_y", self._get_freqs_base(self.DY), persistent=False)
|
| 676 |
+
self.register_buffer("freqs_base_x", self._get_freqs_base(self.DX), persistent=False)
|
| 677 |
+
|
| 678 |
+
def _get_freqs_base(self, dim):
|
| 679 |
+
return 1.0 / (self.theta ** (torch.arange(0, dim, 2, dtype=torch.float32)[: (dim // 2)] / dim))
|
| 680 |
+
|
| 681 |
+
@torch.no_grad()
|
| 682 |
+
def get_frequency_batched(self, freqs_base, pos):
|
| 683 |
+
freqs = torch.einsum("d,bthw->dbthw", freqs_base, pos)
|
| 684 |
+
freqs = freqs.repeat_interleave(2, dim=0)
|
| 685 |
+
return freqs.cos(), freqs.sin()
|
| 686 |
+
|
| 687 |
+
@torch.no_grad()
|
| 688 |
+
@lru_cache(maxsize=32)
|
| 689 |
+
def _get_spatial_meshgrid(self, height, width, device_str):
|
| 690 |
+
device = torch.device(device_str)
|
| 691 |
+
gy = torch.arange(height, device=device, dtype=torch.float32)
|
| 692 |
+
gx = torch.arange(width, device=device, dtype=torch.float32)
|
| 693 |
+
GY, GX = torch.meshgrid(gy, gx, indexing="ij")
|
| 694 |
+
return GY, GX
|
| 695 |
+
|
| 696 |
+
@torch.no_grad()
|
| 697 |
+
def forward(self, frame_indices, height, width, device):
|
| 698 |
+
B = frame_indices.shape[0]
|
| 699 |
+
T = frame_indices.shape[1]
|
| 700 |
+
|
| 701 |
+
frame_indices = frame_indices.to(device=device, dtype=torch.float32)
|
| 702 |
+
GY, GX = self._get_spatial_meshgrid(height, width, str(device))
|
| 703 |
+
|
| 704 |
+
GT = frame_indices[:, :, None, None].expand(B, T, height, width)
|
| 705 |
+
GY_batch = GY[None, None, :, :].expand(B, T, -1, -1)
|
| 706 |
+
GX_batch = GX[None, None, :, :].expand(B, T, -1, -1)
|
| 707 |
+
|
| 708 |
+
FCT, FST = self.get_frequency_batched(self.freqs_base_t, GT)
|
| 709 |
+
FCY, FSY = self.get_frequency_batched(self.freqs_base_y, GY_batch)
|
| 710 |
+
FCX, FSX = self.get_frequency_batched(self.freqs_base_x, GX_batch)
|
| 711 |
+
|
| 712 |
+
result = torch.cat([FCT, FCY, FCX, FST, FSY, FSX], dim=0)
|
| 713 |
+
|
| 714 |
+
return result.permute(1, 0, 2, 3, 4)
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
@maybe_allow_in_graph
|
| 718 |
+
class HeliosTransformerBlock(nn.Module):
|
| 719 |
+
def __init__(
|
| 720 |
+
self,
|
| 721 |
+
dim: int,
|
| 722 |
+
ffn_dim: int,
|
| 723 |
+
num_heads: int,
|
| 724 |
+
qk_norm: str = "rms_norm_across_heads",
|
| 725 |
+
cross_attn_norm: bool = False,
|
| 726 |
+
eps: float = 1e-6,
|
| 727 |
+
added_kv_proj_dim: Optional[int] = None,
|
| 728 |
+
restrict_self_attn: bool = False,
|
| 729 |
+
guidance_cross_attn: bool = False,
|
| 730 |
+
is_train_restrict_lora: bool = False,
|
| 731 |
+
restrict_lora: bool = False,
|
| 732 |
+
restrict_lora_rank: int = 128,
|
| 733 |
+
is_amplify_history: bool = False,
|
| 734 |
+
history_scale_mode: str = "per_head", # [scalar, per_head],
|
| 735 |
+
):
|
| 736 |
+
super().__init__()
|
| 737 |
+
|
| 738 |
+
# 1. Self-attention
|
| 739 |
+
self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 740 |
+
self.attn1 = HeliosAttention(
|
| 741 |
+
dim=dim,
|
| 742 |
+
heads=num_heads,
|
| 743 |
+
dim_head=dim // num_heads,
|
| 744 |
+
eps=eps,
|
| 745 |
+
cross_attention_dim_head=None,
|
| 746 |
+
processor=HeliosAttnProcessor(),
|
| 747 |
+
restrict_self_attn=restrict_self_attn,
|
| 748 |
+
is_train_restrict_lora=is_train_restrict_lora,
|
| 749 |
+
restrict_lora=restrict_lora,
|
| 750 |
+
restrict_lora_rank=restrict_lora_rank,
|
| 751 |
+
is_amplify_history=is_amplify_history,
|
| 752 |
+
history_scale_mode=history_scale_mode,
|
| 753 |
+
)
|
| 754 |
+
|
| 755 |
+
# 2. Cross-attention
|
| 756 |
+
self.attn2 = HeliosAttention(
|
| 757 |
+
dim=dim,
|
| 758 |
+
heads=num_heads,
|
| 759 |
+
dim_head=dim // num_heads,
|
| 760 |
+
eps=eps,
|
| 761 |
+
added_kv_proj_dim=added_kv_proj_dim,
|
| 762 |
+
cross_attention_dim_head=dim // num_heads,
|
| 763 |
+
processor=HeliosAttnProcessor(),
|
| 764 |
+
)
|
| 765 |
+
self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
|
| 766 |
+
|
| 767 |
+
# 3. Feed-forward
|
| 768 |
+
self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
|
| 769 |
+
self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 770 |
+
|
| 771 |
+
self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
|
| 772 |
+
|
| 773 |
+
# 4. Guidance cross-attention
|
| 774 |
+
self.guidance_cross_attn = guidance_cross_attn
|
| 775 |
+
|
| 776 |
+
def forward(
|
| 777 |
+
self,
|
| 778 |
+
hidden_states: torch.Tensor,
|
| 779 |
+
encoder_hidden_states: torch.Tensor,
|
| 780 |
+
temb: torch.Tensor,
|
| 781 |
+
rotary_emb: torch.Tensor,
|
| 782 |
+
navit_hidden_attention_mask: Optional[torch.Tensor] = None,
|
| 783 |
+
navit_encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 784 |
+
original_context_length: int = None,
|
| 785 |
+
original_context_length_list: list = None,
|
| 786 |
+
is_first_denoising_step: bool = False,
|
| 787 |
+
) -> torch.Tensor:
|
| 788 |
+
enable_navit = False
|
| 789 |
+
if len(original_context_length_list) > 1:
|
| 790 |
+
enable_navit = True
|
| 791 |
+
|
| 792 |
+
if temb.ndim == 4:
|
| 793 |
+
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
| 794 |
+
self.scale_shift_table.unsqueeze(0) + temb.float()
|
| 795 |
+
).chunk(6, dim=2)
|
| 796 |
+
# batch_size, seq_len, 1, inner_dim
|
| 797 |
+
shift_msa = shift_msa.squeeze(2)
|
| 798 |
+
scale_msa = scale_msa.squeeze(2)
|
| 799 |
+
gate_msa = gate_msa.squeeze(2)
|
| 800 |
+
c_shift_msa = c_shift_msa.squeeze(2)
|
| 801 |
+
c_scale_msa = c_scale_msa.squeeze(2)
|
| 802 |
+
c_gate_msa = c_gate_msa.squeeze(2)
|
| 803 |
+
else:
|
| 804 |
+
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
| 805 |
+
self.scale_shift_table + temb.float()
|
| 806 |
+
).chunk(6, dim=1)
|
| 807 |
+
|
| 808 |
+
# 1. Self-attention
|
| 809 |
+
norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
|
| 810 |
+
attn_output = self.attn1(
|
| 811 |
+
norm_hidden_states,
|
| 812 |
+
None,
|
| 813 |
+
navit_hidden_attention_mask,
|
| 814 |
+
rotary_emb,
|
| 815 |
+
original_context_length,
|
| 816 |
+
original_context_length_list,
|
| 817 |
+
enable_navit,
|
| 818 |
+
is_first_denoising_step=is_first_denoising_step,
|
| 819 |
+
)
|
| 820 |
+
hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
|
| 821 |
+
|
| 822 |
+
# 2. Cross-attention
|
| 823 |
+
if self.guidance_cross_attn:
|
| 824 |
+
history_seq_len = (hidden_states.shape[1] - original_context_length) // len(original_context_length_list)
|
| 825 |
+
|
| 826 |
+
if enable_navit:
|
| 827 |
+
num_seqs = len(original_context_length_list)
|
| 828 |
+
|
| 829 |
+
hidden_states_list = [None] * num_seqs
|
| 830 |
+
history_hidden_states_list = [None] * num_seqs
|
| 831 |
+
|
| 832 |
+
seq_start = 0
|
| 833 |
+
for idx, cur_seq_len in enumerate(original_context_length_list[::-1]):
|
| 834 |
+
seq_end = seq_start + cur_seq_len + history_seq_len
|
| 835 |
+
cur_hidden_states = hidden_states[:, seq_start:seq_end, :]
|
| 836 |
+
|
| 837 |
+
history_hidden_states_list[idx] = cur_hidden_states[:, :history_seq_len]
|
| 838 |
+
hidden_states_list[idx] = cur_hidden_states[:, history_seq_len:]
|
| 839 |
+
|
| 840 |
+
seq_start += cur_seq_len + history_seq_len
|
| 841 |
+
|
| 842 |
+
hidden_states = torch.cat(hidden_states_list, dim=1)
|
| 843 |
+
|
| 844 |
+
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
| 845 |
+
attn_output = self.attn2(
|
| 846 |
+
norm_hidden_states,
|
| 847 |
+
encoder_hidden_states,
|
| 848 |
+
navit_encoder_attention_mask,
|
| 849 |
+
None,
|
| 850 |
+
original_context_length,
|
| 851 |
+
original_context_length_list,
|
| 852 |
+
enable_navit,
|
| 853 |
+
)
|
| 854 |
+
hidden_states = hidden_states + attn_output
|
| 855 |
+
|
| 856 |
+
seq_start = 0
|
| 857 |
+
for idx, cur_seq_len in enumerate(original_context_length_list[::-1]):
|
| 858 |
+
cur_hidden_states = hidden_states[:, seq_start : seq_start + cur_seq_len, :]
|
| 859 |
+
|
| 860 |
+
hidden_states_list[idx] = torch.cat([history_hidden_states_list[idx], cur_hidden_states], dim=1)
|
| 861 |
+
|
| 862 |
+
seq_start += cur_seq_len
|
| 863 |
+
|
| 864 |
+
hidden_states = torch.cat(hidden_states_list, dim=1)
|
| 865 |
+
else:
|
| 866 |
+
history_hidden_states, hidden_states = (
|
| 867 |
+
hidden_states[:, :history_seq_len],
|
| 868 |
+
hidden_states[:, history_seq_len:],
|
| 869 |
+
)
|
| 870 |
+
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
| 871 |
+
attn_output = self.attn2(
|
| 872 |
+
norm_hidden_states,
|
| 873 |
+
encoder_hidden_states,
|
| 874 |
+
navit_encoder_attention_mask,
|
| 875 |
+
None,
|
| 876 |
+
original_context_length,
|
| 877 |
+
original_context_length_list,
|
| 878 |
+
enable_navit,
|
| 879 |
+
)
|
| 880 |
+
hidden_states = hidden_states + attn_output
|
| 881 |
+
hidden_states = torch.cat([history_hidden_states, hidden_states], dim=1)
|
| 882 |
+
else:
|
| 883 |
+
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
| 884 |
+
attn_output = self.attn2(
|
| 885 |
+
norm_hidden_states,
|
| 886 |
+
encoder_hidden_states,
|
| 887 |
+
navit_encoder_attention_mask,
|
| 888 |
+
None,
|
| 889 |
+
original_context_length,
|
| 890 |
+
original_context_length_list,
|
| 891 |
+
enable_navit,
|
| 892 |
+
)
|
| 893 |
+
hidden_states = hidden_states + attn_output
|
| 894 |
+
|
| 895 |
+
# 3. Feed-forward
|
| 896 |
+
norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
|
| 897 |
+
hidden_states
|
| 898 |
+
)
|
| 899 |
+
ff_output = self.ffn(norm_hidden_states)
|
| 900 |
+
hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
|
| 901 |
+
|
| 902 |
+
return hidden_states
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
class HeliosTransformer3DModel(
|
| 906 |
+
ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin, AttentionMixin
|
| 907 |
+
):
|
| 908 |
+
r"""
|
| 909 |
+
A Transformer model for video-like data used in the Helios model.
|
| 910 |
+
|
| 911 |
+
Args:
|
| 912 |
+
patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
|
| 913 |
+
3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
|
| 914 |
+
num_attention_heads (`int`, defaults to `40`):
|
| 915 |
+
Fixed length for text embeddings.
|
| 916 |
+
attention_head_dim (`int`, defaults to `128`):
|
| 917 |
+
The number of channels in each head.
|
| 918 |
+
in_channels (`int`, defaults to `16`):
|
| 919 |
+
The number of channels in the input.
|
| 920 |
+
out_channels (`int`, defaults to `16`):
|
| 921 |
+
The number of channels in the output.
|
| 922 |
+
text_dim (`int`, defaults to `512`):
|
| 923 |
+
Input dimension for text embeddings.
|
| 924 |
+
freq_dim (`int`, defaults to `256`):
|
| 925 |
+
Dimension for sinusoidal time embeddings.
|
| 926 |
+
ffn_dim (`int`, defaults to `13824`):
|
| 927 |
+
Intermediate dimension in feed-forward network.
|
| 928 |
+
num_layers (`int`, defaults to `40`):
|
| 929 |
+
The number of layers of transformer blocks to use.
|
| 930 |
+
window_size (`Tuple[int]`, defaults to `(-1, -1)`):
|
| 931 |
+
Window size for local attention (-1 indicates global attention).
|
| 932 |
+
cross_attn_norm (`bool`, defaults to `True`):
|
| 933 |
+
Enable cross-attention normalization.
|
| 934 |
+
qk_norm (`bool`, defaults to `True`):
|
| 935 |
+
Enable query/key normalization.
|
| 936 |
+
eps (`float`, defaults to `1e-6`):
|
| 937 |
+
Epsilon value for normalization layers.
|
| 938 |
+
add_img_emb (`bool`, defaults to `False`):
|
| 939 |
+
Whether to use img_emb.
|
| 940 |
+
added_kv_proj_dim (`int`, *optional*, defaults to `None`):
|
| 941 |
+
The number of channels to use for the added key and value projections. If `None`, no projection is used.
|
| 942 |
+
"""
|
| 943 |
+
|
| 944 |
+
_supports_gradient_checkpointing = True
|
| 945 |
+
_skip_layerwise_casting_patterns = [
|
| 946 |
+
"patch_embedding",
|
| 947 |
+
"patch_short",
|
| 948 |
+
"patch_mid",
|
| 949 |
+
"patch_long",
|
| 950 |
+
"condition_embedder",
|
| 951 |
+
"norm",
|
| 952 |
+
]
|
| 953 |
+
_no_split_modules = ["HeliosTransformerBlock", "HeliosOutputNorm"]
|
| 954 |
+
_keep_in_fp32_modules = [
|
| 955 |
+
"time_embedder",
|
| 956 |
+
"scale_shift_table",
|
| 957 |
+
"norm1",
|
| 958 |
+
"norm2",
|
| 959 |
+
"norm3",
|
| 960 |
+
"history_key_scale",
|
| 961 |
+
]
|
| 962 |
+
_keys_to_ignore_on_load_unexpected = ["norm_added_q"]
|
| 963 |
+
_repeated_blocks = ["HeliosTransformerBlock"]
|
| 964 |
+
_cp_plan = {
|
| 965 |
+
# Input split at attn level and ffn level.
|
| 966 |
+
"blocks.*.attn1": {
|
| 967 |
+
"hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 968 |
+
"rotary_emb": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 969 |
+
},
|
| 970 |
+
"blocks.*.attn2": {
|
| 971 |
+
"hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 972 |
+
},
|
| 973 |
+
"blocks.*.ffn": {
|
| 974 |
+
"hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 975 |
+
},
|
| 976 |
+
# Output gather at attn level and ffn level.
|
| 977 |
+
**{f"blocks.{i}.attn1": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)},
|
| 978 |
+
**{f"blocks.{i}.attn2": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)},
|
| 979 |
+
**{f"blocks.{i}.ffn": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)},
|
| 980 |
+
}
|
| 981 |
+
|
| 982 |
+
@register_to_config
|
| 983 |
+
def __init__(
|
| 984 |
+
self,
|
| 985 |
+
patch_size: tuple[int, ...] = (1, 2, 2),
|
| 986 |
+
num_attention_heads: int = 40,
|
| 987 |
+
attention_head_dim: int = 128,
|
| 988 |
+
in_channels: int = 16,
|
| 989 |
+
out_channels: int = 16,
|
| 990 |
+
text_dim: int = 4096,
|
| 991 |
+
freq_dim: int = 256,
|
| 992 |
+
ffn_dim: int = 13824,
|
| 993 |
+
num_layers: int = 40,
|
| 994 |
+
cross_attn_norm: bool = True,
|
| 995 |
+
qk_norm: str | None = "rms_norm_across_heads",
|
| 996 |
+
eps: float = 1e-6,
|
| 997 |
+
image_dim: int | None = None,
|
| 998 |
+
added_kv_proj_dim: int | None = None,
|
| 999 |
+
rope_dim: tuple[int, ...] = (44, 42, 42),
|
| 1000 |
+
rope_theta: float = 10000.0,
|
| 1001 |
+
restrict_self_attn: bool = False,
|
| 1002 |
+
guidance_cross_attn: bool = False,
|
| 1003 |
+
is_train_restrict_lora: bool = False,
|
| 1004 |
+
restrict_lora: bool = False,
|
| 1005 |
+
restrict_lora_rank: int = 128,
|
| 1006 |
+
zero_history_timestep: bool = False,
|
| 1007 |
+
has_multi_term_memory_patch: bool = False,
|
| 1008 |
+
is_amplify_history: bool = False,
|
| 1009 |
+
history_scale_mode: str = "per_head", # [scalar, per_head]
|
| 1010 |
+
is_use_gan: bool = False,
|
| 1011 |
+
is_use_gan_hooks: bool = False,
|
| 1012 |
+
is_use_gan_final: bool = False,
|
| 1013 |
+
gan_cond_map_dim: int = 768,
|
| 1014 |
+
gan_hooks: List[int] = [5, 15, 25, 35],
|
| 1015 |
+
) -> None:
|
| 1016 |
+
super().__init__()
|
| 1017 |
+
|
| 1018 |
+
inner_dim = num_attention_heads * attention_head_dim
|
| 1019 |
+
out_channels = out_channels or in_channels
|
| 1020 |
+
|
| 1021 |
+
# 1. Patch & position embedding
|
| 1022 |
+
self.rope = HeliosRotaryPosEmbed(rope_dim=rope_dim, theta=rope_theta)
|
| 1023 |
+
self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
|
| 1024 |
+
|
| 1025 |
+
# 2. Condition embeddings
|
| 1026 |
+
self.condition_embedder = HeliosTimeTextEmbedding(
|
| 1027 |
+
dim=inner_dim,
|
| 1028 |
+
time_freq_dim=freq_dim,
|
| 1029 |
+
time_proj_dim=inner_dim * 6,
|
| 1030 |
+
text_embed_dim=text_dim,
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
# 3. Transformer blocks
|
| 1034 |
+
self.blocks = nn.ModuleList(
|
| 1035 |
+
[
|
| 1036 |
+
HeliosTransformerBlock(
|
| 1037 |
+
inner_dim,
|
| 1038 |
+
ffn_dim,
|
| 1039 |
+
num_attention_heads,
|
| 1040 |
+
qk_norm,
|
| 1041 |
+
cross_attn_norm,
|
| 1042 |
+
eps,
|
| 1043 |
+
added_kv_proj_dim,
|
| 1044 |
+
restrict_self_attn=restrict_self_attn,
|
| 1045 |
+
guidance_cross_attn=guidance_cross_attn,
|
| 1046 |
+
is_train_restrict_lora=is_train_restrict_lora,
|
| 1047 |
+
restrict_lora=restrict_lora,
|
| 1048 |
+
restrict_lora_rank=restrict_lora_rank,
|
| 1049 |
+
is_amplify_history=is_amplify_history,
|
| 1050 |
+
history_scale_mode=history_scale_mode,
|
| 1051 |
+
)
|
| 1052 |
+
for _ in range(num_layers)
|
| 1053 |
+
]
|
| 1054 |
+
)
|
| 1055 |
+
|
| 1056 |
+
# 4. Output norm & projection
|
| 1057 |
+
self.norm_out = HeliosOutputNorm(inner_dim, eps, elementwise_affine=False)
|
| 1058 |
+
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
|
| 1059 |
+
|
| 1060 |
+
self.init_weights()
|
| 1061 |
+
|
| 1062 |
+
# 5. Initial Stage1
|
| 1063 |
+
self.zero_history_timestep = zero_history_timestep
|
| 1064 |
+
self.inner_dim = inner_dim
|
| 1065 |
+
if has_multi_term_memory_patch:
|
| 1066 |
+
self.patch_short = nn.Conv3d(in_channels, self.inner_dim, kernel_size=(1, 2, 2), stride=(1, 2, 2))
|
| 1067 |
+
self.patch_mid = nn.Conv3d(in_channels, self.inner_dim, kernel_size=(2, 4, 4), stride=(2, 4, 4))
|
| 1068 |
+
self.patch_long = nn.Conv3d(in_channels, self.inner_dim, kernel_size=(4, 8, 8), stride=(4, 8, 8))
|
| 1069 |
+
self.initialize_weight_from_another_conv3d(self.patch_embedding)
|
| 1070 |
+
|
| 1071 |
+
# 6. Initial Gan
|
| 1072 |
+
self.is_use_gan = is_use_gan
|
| 1073 |
+
if is_use_gan:
|
| 1074 |
+
self.is_use_gan_hooks = is_use_gan_hooks
|
| 1075 |
+
self.is_use_gan_final = is_use_gan_final
|
| 1076 |
+
if is_use_gan_hooks:
|
| 1077 |
+
gan_heads = []
|
| 1078 |
+
self.gan_hooks = gan_hooks
|
| 1079 |
+
for hook in self.gan_hooks:
|
| 1080 |
+
gan_heads.append((str(hook), Discriminator3DHead(inner_dim, gan_cond_map_dim)))
|
| 1081 |
+
self.gan_heads = nn.ModuleDict(gan_heads)
|
| 1082 |
+
if is_use_gan_final:
|
| 1083 |
+
self.gan_final_head = Discriminator3DHead(out_channels, gan_cond_map_dim)
|
| 1084 |
+
|
| 1085 |
+
self.gradient_checkpointing = False
|
| 1086 |
+
|
| 1087 |
+
@torch.no_grad()
|
| 1088 |
+
def initialize_weight_from_another_conv3d(self, another_layer):
|
| 1089 |
+
weight = another_layer.weight.detach().clone()
|
| 1090 |
+
bias = another_layer.bias.detach().clone()
|
| 1091 |
+
|
| 1092 |
+
weight = weight[:, :16, :, :, :]
|
| 1093 |
+
|
| 1094 |
+
sd = {
|
| 1095 |
+
"patch_short.weight": weight.clone(),
|
| 1096 |
+
"patch_short.bias": bias.clone(),
|
| 1097 |
+
"patch_mid.weight": einops.repeat(weight, "b c t h w -> b c (t tk) (h hk) (w wk)", tk=2, hk=2, wk=2) / 8.0,
|
| 1098 |
+
"patch_mid.bias": bias.clone(),
|
| 1099 |
+
"patch_long.weight": einops.repeat(weight, "b c t h w -> b c (t tk) (h hk) (w wk)", tk=4, hk=4, wk=4)
|
| 1100 |
+
/ 64.0,
|
| 1101 |
+
"patch_long.bias": bias.clone(),
|
| 1102 |
+
}
|
| 1103 |
+
|
| 1104 |
+
sd = {k: v.clone() for k, v in sd.items()}
|
| 1105 |
+
|
| 1106 |
+
self.load_state_dict(sd, strict=False)
|
| 1107 |
+
|
| 1108 |
+
def gradient_checkpointing_method(self, block, *args):
|
| 1109 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
| 1110 |
+
result = self._gradient_checkpointing_func(block, *args)
|
| 1111 |
+
else:
|
| 1112 |
+
result = block(*args)
|
| 1113 |
+
return result
|
| 1114 |
+
|
| 1115 |
+
def enable_kv_cache(self):
|
| 1116 |
+
for block in self.blocks:
|
| 1117 |
+
if hasattr(block.attn1, "processor") and hasattr(block.attn1.processor, "enable_cache"):
|
| 1118 |
+
block.attn1.processor.enable_cache()
|
| 1119 |
+
|
| 1120 |
+
def disable_kv_cache(self):
|
| 1121 |
+
for block in self.blocks:
|
| 1122 |
+
if hasattr(block.attn1, "processor") and hasattr(block.attn1.processor, "disable_cache"):
|
| 1123 |
+
block.attn1.processor.disable_cache()
|
| 1124 |
+
|
| 1125 |
+
def clear_kv_cache(self):
|
| 1126 |
+
for block in self.blocks:
|
| 1127 |
+
if hasattr(block.attn1, "processor") and hasattr(block.attn1.processor, "clear_cache"):
|
| 1128 |
+
block.attn1.processor.clear_cache()
|
| 1129 |
+
|
| 1130 |
+
def process_input_hidden_states(
|
| 1131 |
+
self,
|
| 1132 |
+
latents,
|
| 1133 |
+
indices_hidden_states=None,
|
| 1134 |
+
indices_latents_history_short=None,
|
| 1135 |
+
indices_latents_history_mid=None,
|
| 1136 |
+
indices_latents_history_long=None,
|
| 1137 |
+
latents_history_short=None,
|
| 1138 |
+
latents_history_mid=None,
|
| 1139 |
+
latents_history_long=None,
|
| 1140 |
+
):
|
| 1141 |
+
height_list = []
|
| 1142 |
+
width_list = []
|
| 1143 |
+
temporal_list = []
|
| 1144 |
+
seq_list = []
|
| 1145 |
+
if isinstance(latents, list):
|
| 1146 |
+
hidden_states = None
|
| 1147 |
+
rope_freqs = None
|
| 1148 |
+
for idx, cur_hidden_states in enumerate(latents):
|
| 1149 |
+
cur_hidden_states = self.gradient_checkpointing_method(
|
| 1150 |
+
self.patch_embedding, cur_hidden_states.to(self.device, dtype=self.dtype)
|
| 1151 |
+
)
|
| 1152 |
+
B, C, T, H, W = cur_hidden_states.shape
|
| 1153 |
+
|
| 1154 |
+
cur_hidden_states = cur_hidden_states.flatten(2).transpose(1, 2)
|
| 1155 |
+
|
| 1156 |
+
if indices_hidden_states is None:
|
| 1157 |
+
indices_hidden_states = torch.arange(0, T).unsqueeze(0).expand(B, -1)
|
| 1158 |
+
|
| 1159 |
+
cur_indices_latents = indices_hidden_states
|
| 1160 |
+
cur_rope_freqs = self.rope(
|
| 1161 |
+
frame_indices=cur_indices_latents, height=H, width=W, device=cur_hidden_states.device
|
| 1162 |
+
)
|
| 1163 |
+
cur_rope_freqs = cur_rope_freqs.flatten(2).transpose(1, 2)
|
| 1164 |
+
|
| 1165 |
+
height_list.append(H)
|
| 1166 |
+
width_list.append(W)
|
| 1167 |
+
temporal_list.append(T)
|
| 1168 |
+
seq_list.append(cur_hidden_states.shape[1])
|
| 1169 |
+
|
| 1170 |
+
if hidden_states is None:
|
| 1171 |
+
hidden_states = cur_hidden_states
|
| 1172 |
+
rope_freqs = cur_rope_freqs
|
| 1173 |
+
else:
|
| 1174 |
+
hidden_states = torch.cat([cur_hidden_states, hidden_states], dim=1)
|
| 1175 |
+
rope_freqs = torch.cat([cur_rope_freqs, rope_freqs], dim=1)
|
| 1176 |
+
else:
|
| 1177 |
+
hidden_states = self.gradient_checkpointing_method(self.patch_embedding, latents)
|
| 1178 |
+
B, C, T, H, W = hidden_states.shape
|
| 1179 |
+
|
| 1180 |
+
if indices_hidden_states is None:
|
| 1181 |
+
indices_hidden_states = torch.arange(0, T).unsqueeze(0).expand(B, -1)
|
| 1182 |
+
|
| 1183 |
+
hidden_states = hidden_states.flatten(2).transpose(
|
| 1184 |
+
1, 2
|
| 1185 |
+
) # torch.Size([1, 3072, 9, 44, 34]) -> torch.Size([1, 13464, 3072])
|
| 1186 |
+
|
| 1187 |
+
rope_freqs = self.rope(
|
| 1188 |
+
frame_indices=indices_hidden_states,
|
| 1189 |
+
height=H,
|
| 1190 |
+
width=W,
|
| 1191 |
+
device=hidden_states.device,
|
| 1192 |
+
) # torch.Size([1, 9]) -> torch.Size([1, 256, 9, 44, 34])
|
| 1193 |
+
rope_freqs = rope_freqs.flatten(2).transpose(1, 2) # torch.Size([1, 13464, 256])
|
| 1194 |
+
|
| 1195 |
+
height_list.append(H)
|
| 1196 |
+
width_list.append(W)
|
| 1197 |
+
temporal_list.append(T)
|
| 1198 |
+
seq_list.append(hidden_states.shape[1])
|
| 1199 |
+
|
| 1200 |
+
# Process short history latents
|
| 1201 |
+
if latents_history_short is not None and indices_latents_history_short is not None:
|
| 1202 |
+
latents_history_short = latents_history_short.to(hidden_states)
|
| 1203 |
+
latents_history_short = self.gradient_checkpointing_method(self.patch_short, latents_history_short)
|
| 1204 |
+
_, _, _, H1, W1 = latents_history_short.shape
|
| 1205 |
+
latents_history_short = latents_history_short.flatten(2).transpose(1, 2)
|
| 1206 |
+
|
| 1207 |
+
rope_freqs_history_short = self.rope(
|
| 1208 |
+
frame_indices=indices_latents_history_short,
|
| 1209 |
+
height=H1,
|
| 1210 |
+
width=W1,
|
| 1211 |
+
device=latents_history_short.device,
|
| 1212 |
+
)
|
| 1213 |
+
rope_freqs_history_short = rope_freqs_history_short.flatten(2).transpose(1, 2)
|
| 1214 |
+
|
| 1215 |
+
hidden_states = torch.cat([latents_history_short, hidden_states], dim=1)
|
| 1216 |
+
rope_freqs = torch.cat([rope_freqs_history_short, rope_freqs], dim=1)
|
| 1217 |
+
|
| 1218 |
+
# Process mid history latents
|
| 1219 |
+
if latents_history_mid is not None and indices_latents_history_mid is not None:
|
| 1220 |
+
latents_history_mid = latents_history_mid.to(hidden_states)
|
| 1221 |
+
latents_history_mid = pad_for_3d_conv(latents_history_mid, (2, 4, 4))
|
| 1222 |
+
latents_history_mid = self.gradient_checkpointing_method(self.patch_mid, latents_history_mid)
|
| 1223 |
+
latents_history_mid = latents_history_mid.flatten(2).transpose(1, 2)
|
| 1224 |
+
|
| 1225 |
+
rope_freqs_history_mid = self.rope(
|
| 1226 |
+
frame_indices=indices_latents_history_mid,
|
| 1227 |
+
height=H1,
|
| 1228 |
+
width=W1,
|
| 1229 |
+
device=latents_history_mid.device,
|
| 1230 |
+
)
|
| 1231 |
+
rope_freqs_history_mid = pad_for_3d_conv(rope_freqs_history_mid, (2, 2, 2))
|
| 1232 |
+
rope_freqs_history_mid = center_down_sample_3d(rope_freqs_history_mid, (2, 2, 2))
|
| 1233 |
+
rope_freqs_history_mid = rope_freqs_history_mid.flatten(2).transpose(1, 2)
|
| 1234 |
+
|
| 1235 |
+
hidden_states = torch.cat([latents_history_mid, hidden_states], dim=1)
|
| 1236 |
+
rope_freqs = torch.cat([rope_freqs_history_mid, rope_freqs], dim=1)
|
| 1237 |
+
|
| 1238 |
+
# Process long history latents
|
| 1239 |
+
if latents_history_long is not None and indices_latents_history_long is not None:
|
| 1240 |
+
latents_history_long = latents_history_long.to(hidden_states)
|
| 1241 |
+
latents_history_long = pad_for_3d_conv(latents_history_long, (4, 8, 8))
|
| 1242 |
+
latents_history_long = self.gradient_checkpointing_method(self.patch_long, latents_history_long)
|
| 1243 |
+
latents_history_long = latents_history_long.flatten(2).transpose(1, 2)
|
| 1244 |
+
|
| 1245 |
+
rope_freqs_history_long = self.rope(
|
| 1246 |
+
frame_indices=indices_latents_history_long,
|
| 1247 |
+
height=H1,
|
| 1248 |
+
width=W1,
|
| 1249 |
+
device=latents_history_long.device,
|
| 1250 |
+
)
|
| 1251 |
+
rope_freqs_history_long = pad_for_3d_conv(rope_freqs_history_long, (4, 4, 4))
|
| 1252 |
+
rope_freqs_history_long = center_down_sample_3d(rope_freqs_history_long, (4, 4, 4))
|
| 1253 |
+
rope_freqs_history_long = rope_freqs_history_long.flatten(2).transpose(1, 2)
|
| 1254 |
+
|
| 1255 |
+
hidden_states = torch.cat([latents_history_long, hidden_states], dim=1)
|
| 1256 |
+
rope_freqs = torch.cat([rope_freqs_history_long, rope_freqs], dim=1)
|
| 1257 |
+
|
| 1258 |
+
return (
|
| 1259 |
+
hidden_states,
|
| 1260 |
+
rope_freqs,
|
| 1261 |
+
height_list,
|
| 1262 |
+
width_list,
|
| 1263 |
+
temporal_list,
|
| 1264 |
+
seq_list,
|
| 1265 |
+
)
|
| 1266 |
+
|
| 1267 |
+
@apply_lora_scale("attention_kwargs")
|
| 1268 |
+
def forward(
|
| 1269 |
+
self,
|
| 1270 |
+
hidden_states: torch.Tensor,
|
| 1271 |
+
timestep: torch.LongTensor,
|
| 1272 |
+
encoder_hidden_states: torch.Tensor,
|
| 1273 |
+
# ------------ Stage 1 ------------
|
| 1274 |
+
indices_hidden_states=None,
|
| 1275 |
+
indices_latents_history_short=None,
|
| 1276 |
+
indices_latents_history_mid=None,
|
| 1277 |
+
indices_latents_history_long=None,
|
| 1278 |
+
latents_history_short=None,
|
| 1279 |
+
latents_history_mid=None,
|
| 1280 |
+
latents_history_long=None,
|
| 1281 |
+
is_first_denoising_step: bool = False,
|
| 1282 |
+
# ------------ GAN ------------
|
| 1283 |
+
gan_mode: bool = False,
|
| 1284 |
+
return_dict: bool = True,
|
| 1285 |
+
attention_kwargs: dict[str, Any] | None = None,
|
| 1286 |
+
) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
|
| 1287 |
+
assert (
|
| 1288 |
+
len(
|
| 1289 |
+
{
|
| 1290 |
+
x is None
|
| 1291 |
+
for x in [
|
| 1292 |
+
indices_hidden_states,
|
| 1293 |
+
indices_latents_history_short,
|
| 1294 |
+
indices_latents_history_mid,
|
| 1295 |
+
indices_latents_history_long,
|
| 1296 |
+
latents_history_short,
|
| 1297 |
+
latents_history_mid,
|
| 1298 |
+
latents_history_long,
|
| 1299 |
+
]
|
| 1300 |
+
}
|
| 1301 |
+
)
|
| 1302 |
+
== 1
|
| 1303 |
+
), "All history latents and indices must either all exist or all be None"
|
| 1304 |
+
|
| 1305 |
+
if indices_hidden_states is not None and indices_hidden_states.ndim == 1:
|
| 1306 |
+
indices_hidden_states = indices_hidden_states.unsqueeze(0)
|
| 1307 |
+
if indices_latents_history_short is not None and indices_latents_history_short.ndim == 1:
|
| 1308 |
+
indices_latents_history_short = indices_latents_history_short.unsqueeze(0)
|
| 1309 |
+
if indices_latents_history_mid is not None and indices_latents_history_mid.ndim == 1:
|
| 1310 |
+
indices_latents_history_mid = indices_latents_history_mid.unsqueeze(0)
|
| 1311 |
+
if indices_latents_history_long is not None and indices_latents_history_long.ndim == 1:
|
| 1312 |
+
indices_latents_history_long = indices_latents_history_long.unsqueeze(0)
|
| 1313 |
+
|
| 1314 |
+
if gan_mode:
|
| 1315 |
+
assert self.is_use_gan
|
| 1316 |
+
|
| 1317 |
+
if isinstance(hidden_states, list):
|
| 1318 |
+
assert gan_mode is False and self.is_use_gan is False
|
| 1319 |
+
enable_navit = True
|
| 1320 |
+
navit_len = len(hidden_states)
|
| 1321 |
+
batch_size = hidden_states[0].shape[0]
|
| 1322 |
+
else:
|
| 1323 |
+
enable_navit = False
|
| 1324 |
+
batch_size = hidden_states.shape[0]
|
| 1325 |
+
p_t, p_h, p_w = self.config.patch_size
|
| 1326 |
+
|
| 1327 |
+
(
|
| 1328 |
+
hidden_states,
|
| 1329 |
+
rotary_emb,
|
| 1330 |
+
post_patch_height_list,
|
| 1331 |
+
post_patch_width_list,
|
| 1332 |
+
post_patch_num_frames_list,
|
| 1333 |
+
original_context_length_list,
|
| 1334 |
+
) = self.process_input_hidden_states(
|
| 1335 |
+
latents=hidden_states,
|
| 1336 |
+
indices_hidden_states=indices_hidden_states,
|
| 1337 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1338 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1339 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1340 |
+
latents_history_short=latents_history_short,
|
| 1341 |
+
latents_history_mid=latents_history_mid,
|
| 1342 |
+
latents_history_long=latents_history_long,
|
| 1343 |
+
) # hidden: [high, mid, low] -> [low, mid, high]
|
| 1344 |
+
post_patch_num_frames = sum(post_patch_num_frames_list)
|
| 1345 |
+
post_patch_height = sum(post_patch_height_list)
|
| 1346 |
+
post_patch_width = sum(post_patch_width_list)
|
| 1347 |
+
original_context_length = sum(original_context_length_list)
|
| 1348 |
+
history_context_length = hidden_states.shape[1] - original_context_length
|
| 1349 |
+
|
| 1350 |
+
if indices_hidden_states is not None and self.zero_history_timestep:
|
| 1351 |
+
if isinstance(timestep, list):
|
| 1352 |
+
timestep_t0 = torch.zeros((1), dtype=timestep[0].dtype, device=timestep[0].device)
|
| 1353 |
+
else:
|
| 1354 |
+
timestep_t0 = torch.zeros((1), dtype=timestep.dtype, device=timestep.device)
|
| 1355 |
+
temb_t0, timestep_proj_t0, _ = self.condition_embedder(
|
| 1356 |
+
timestep_t0, encoder_hidden_states, is_return_encoder_hidden_states=False
|
| 1357 |
+
)
|
| 1358 |
+
temb_t0 = temb_t0.unsqueeze(1).expand(batch_size, history_context_length, -1)
|
| 1359 |
+
timestep_proj_t0 = (
|
| 1360 |
+
timestep_proj_t0.unflatten(-1, (6, -1))
|
| 1361 |
+
.view(1, 6, 1, -1)
|
| 1362 |
+
.expand(batch_size, -1, history_context_length, -1)
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
navit_hidden_attention_mask = None
|
| 1366 |
+
navit_encoder_attention_mask = None
|
| 1367 |
+
if enable_navit:
|
| 1368 |
+
assert navit_len == len(original_context_length_list)
|
| 1369 |
+
navit_hidden_attention_mask, navit_encoder_attention_mask, navit_history_hidden_attention_mask = (
|
| 1370 |
+
create_navit_attention_masks(
|
| 1371 |
+
batch_size=batch_size,
|
| 1372 |
+
original_context_length_list=original_context_length_list[::-1],
|
| 1373 |
+
history_context_length=history_context_length,
|
| 1374 |
+
encoder_hidden_states_seq_len=encoder_hidden_states.shape[1],
|
| 1375 |
+
device=hidden_states.device,
|
| 1376 |
+
restrict_self_attn=self.config.restrict_self_attn,
|
| 1377 |
+
guidance_cross_attn=self.config.guidance_cross_attn,
|
| 1378 |
+
)
|
| 1379 |
+
)
|
| 1380 |
+
navit_hidden_attention_mask = [navit_hidden_attention_mask, navit_history_hidden_attention_mask]
|
| 1381 |
+
|
| 1382 |
+
history_hidden_states, hidden_states = (
|
| 1383 |
+
hidden_states[:, :history_context_length],
|
| 1384 |
+
hidden_states[:, history_context_length:],
|
| 1385 |
+
)
|
| 1386 |
+
history_rotary_emb, rotary_emb = (
|
| 1387 |
+
rotary_emb[:, :history_context_length],
|
| 1388 |
+
rotary_emb[:, history_context_length:],
|
| 1389 |
+
)
|
| 1390 |
+
timestep = timestep[::-1]
|
| 1391 |
+
|
| 1392 |
+
hidden_states_list = [None] * navit_len
|
| 1393 |
+
rotary_emb_list = [None] * navit_len
|
| 1394 |
+
temb_list = [None] * navit_len
|
| 1395 |
+
timestep_proj_list = [None] * navit_len
|
| 1396 |
+
|
| 1397 |
+
seq_start = 0
|
| 1398 |
+
for idx, cur_seq_len in zip(range(navit_len), original_context_length_list[::-1]):
|
| 1399 |
+
cur_hidden_states = hidden_states[:, seq_start : seq_start + cur_seq_len, :]
|
| 1400 |
+
cur_rotary_emb = rotary_emb[:, seq_start : seq_start + cur_seq_len, :]
|
| 1401 |
+
|
| 1402 |
+
hidden_states_list[idx] = torch.cat([history_hidden_states, cur_hidden_states], dim=1)
|
| 1403 |
+
rotary_emb_list[idx] = torch.cat([history_rotary_emb, cur_rotary_emb], dim=1)
|
| 1404 |
+
|
| 1405 |
+
seq_start += cur_seq_len
|
| 1406 |
+
|
| 1407 |
+
if idx == 0:
|
| 1408 |
+
cur_temb, cur_timestep_proj, encoder_hidden_states = self.condition_embedder(
|
| 1409 |
+
timestep[idx], encoder_hidden_states
|
| 1410 |
+
)
|
| 1411 |
+
else:
|
| 1412 |
+
cur_temb, cur_timestep_proj, _ = self.condition_embedder(
|
| 1413 |
+
timestep[idx], encoder_hidden_states, is_return_encoder_hidden_states=False
|
| 1414 |
+
)
|
| 1415 |
+
|
| 1416 |
+
cur_temb = cur_temb.view(batch_size, 1, -1).expand(-1, cur_seq_len, -1)
|
| 1417 |
+
cur_timestep_proj = cur_timestep_proj.view(batch_size, 6, 1, -1).expand(-1, -1, cur_seq_len, -1)
|
| 1418 |
+
|
| 1419 |
+
if self.zero_history_timestep:
|
| 1420 |
+
temb_list[idx] = torch.cat([temb_t0, cur_temb], dim=1)
|
| 1421 |
+
timestep_proj_list[idx] = torch.cat([timestep_proj_t0, cur_timestep_proj], dim=2)
|
| 1422 |
+
else:
|
| 1423 |
+
temb_list[idx] = cur_temb
|
| 1424 |
+
timestep_proj_list[idx] = cur_timestep_proj
|
| 1425 |
+
|
| 1426 |
+
hidden_states = torch.cat(hidden_states_list, dim=1)
|
| 1427 |
+
rotary_emb = torch.cat(rotary_emb_list, dim=1)
|
| 1428 |
+
temb = torch.cat(temb_list, dim=1)
|
| 1429 |
+
timestep_proj = torch.cat(timestep_proj_list, dim=2)
|
| 1430 |
+
else:
|
| 1431 |
+
temb, timestep_proj, encoder_hidden_states = self.condition_embedder(timestep, encoder_hidden_states)
|
| 1432 |
+
timestep_proj = timestep_proj.unflatten(-1, (6, -1))
|
| 1433 |
+
|
| 1434 |
+
if indices_hidden_states is not None and not self.zero_history_timestep:
|
| 1435 |
+
main_repeat_size = hidden_states.shape[1]
|
| 1436 |
+
else:
|
| 1437 |
+
main_repeat_size = original_context_length
|
| 1438 |
+
temb = temb.view(batch_size, 1, -1).expand(batch_size, main_repeat_size, -1)
|
| 1439 |
+
timestep_proj = timestep_proj.view(batch_size, 6, 1, -1).expand(batch_size, 6, main_repeat_size, -1)
|
| 1440 |
+
|
| 1441 |
+
if indices_hidden_states is not None and self.zero_history_timestep:
|
| 1442 |
+
temb = torch.cat([temb_t0, temb], dim=1)
|
| 1443 |
+
timestep_proj = torch.cat([timestep_proj_t0, timestep_proj], dim=2)
|
| 1444 |
+
|
| 1445 |
+
if timestep_proj.ndim == 4:
|
| 1446 |
+
timestep_proj = timestep_proj.permute(0, 2, 1, 3)
|
| 1447 |
+
|
| 1448 |
+
# 4. Transformer blocks
|
| 1449 |
+
logits_hidden = []
|
| 1450 |
+
hidden_states = hidden_states.contiguous()
|
| 1451 |
+
encoder_hidden_states = encoder_hidden_states.contiguous()
|
| 1452 |
+
rotary_emb = rotary_emb.contiguous()
|
| 1453 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
| 1454 |
+
for iidx, block in enumerate(self.blocks):
|
| 1455 |
+
hidden_states = self._gradient_checkpointing_func(
|
| 1456 |
+
block,
|
| 1457 |
+
hidden_states,
|
| 1458 |
+
encoder_hidden_states,
|
| 1459 |
+
timestep_proj,
|
| 1460 |
+
rotary_emb,
|
| 1461 |
+
navit_hidden_attention_mask,
|
| 1462 |
+
navit_encoder_attention_mask,
|
| 1463 |
+
original_context_length,
|
| 1464 |
+
original_context_length_list,
|
| 1465 |
+
is_first_denoising_step,
|
| 1466 |
+
)
|
| 1467 |
+
if gan_mode and self.is_use_gan and self.is_use_gan_hooks and iidx in self.gan_hooks:
|
| 1468 |
+
logits_hidden.append(hidden_states[:, -original_context_length:, :])
|
| 1469 |
+
else:
|
| 1470 |
+
for iidx, block in enumerate(self.blocks):
|
| 1471 |
+
hidden_states = block(
|
| 1472 |
+
hidden_states,
|
| 1473 |
+
encoder_hidden_states,
|
| 1474 |
+
timestep_proj,
|
| 1475 |
+
rotary_emb,
|
| 1476 |
+
navit_hidden_attention_mask,
|
| 1477 |
+
navit_encoder_attention_mask,
|
| 1478 |
+
original_context_length,
|
| 1479 |
+
original_context_length_list,
|
| 1480 |
+
is_first_denoising_step,
|
| 1481 |
+
)
|
| 1482 |
+
if gan_mode and self.is_use_gan and self.is_use_gan_hooks and iidx in self.gan_hooks:
|
| 1483 |
+
logits_hidden.append(hidden_states[:, -original_context_length:, :])
|
| 1484 |
+
|
| 1485 |
+
# 5. Output norm, projection & unpatchify
|
| 1486 |
+
if temb.ndim == 3:
|
| 1487 |
+
if not enable_navit:
|
| 1488 |
+
temb = temb[:, -original_context_length:, :]
|
| 1489 |
+
shift, scale = (self.norm_out.scale_shift_table.unsqueeze(0).to(temb.device) + temb.unsqueeze(2)).chunk(
|
| 1490 |
+
2, dim=2
|
| 1491 |
+
)
|
| 1492 |
+
shift = shift.squeeze(2)
|
| 1493 |
+
scale = scale.squeeze(2)
|
| 1494 |
+
else:
|
| 1495 |
+
# batch_size, inner_dim
|
| 1496 |
+
shift, scale = (self.norm_out.scale_shift_table.to(temb.device) + temb.unsqueeze(1)).chunk(2, dim=1)
|
| 1497 |
+
|
| 1498 |
+
# Move the shift and scale tensors to the same device as hidden_states.
|
| 1499 |
+
# When using multi-GPU inference via accelerate these will be on the
|
| 1500 |
+
# first device rather than the last device, which hidden_states ends up
|
| 1501 |
+
# on.
|
| 1502 |
+
shift = shift.to(hidden_states.device)
|
| 1503 |
+
scale = scale.to(hidden_states.device)
|
| 1504 |
+
|
| 1505 |
+
if enable_navit:
|
| 1506 |
+
hidden_states = (self.norm_out.norm(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
|
| 1507 |
+
|
| 1508 |
+
output = []
|
| 1509 |
+
seq_start = 0
|
| 1510 |
+
for (
|
| 1511 |
+
cur_original_context_length,
|
| 1512 |
+
cur_post_patch_num_frames,
|
| 1513 |
+
cur_post_patch_height,
|
| 1514 |
+
cur_post_patch_width,
|
| 1515 |
+
) in zip(
|
| 1516 |
+
reversed(original_context_length_list),
|
| 1517 |
+
reversed(post_patch_num_frames_list),
|
| 1518 |
+
reversed(post_patch_height_list),
|
| 1519 |
+
reversed(post_patch_width_list),
|
| 1520 |
+
):
|
| 1521 |
+
cur_hidden_states = hidden_states[
|
| 1522 |
+
:, seq_start : seq_start + cur_original_context_length + history_context_length, :
|
| 1523 |
+
] # (B, T*H*W, C)
|
| 1524 |
+
cur_hidden_states = cur_hidden_states[:, history_context_length:, :]
|
| 1525 |
+
cur_hidden_states = self.proj_out(cur_hidden_states)
|
| 1526 |
+
seq_start += cur_original_context_length + history_context_length
|
| 1527 |
+
|
| 1528 |
+
cur_hidden_states = cur_hidden_states.reshape(
|
| 1529 |
+
batch_size,
|
| 1530 |
+
cur_post_patch_num_frames,
|
| 1531 |
+
cur_post_patch_height,
|
| 1532 |
+
cur_post_patch_width,
|
| 1533 |
+
p_t,
|
| 1534 |
+
p_h,
|
| 1535 |
+
p_w,
|
| 1536 |
+
-1,
|
| 1537 |
+
)
|
| 1538 |
+
cur_hidden_states = cur_hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
|
| 1539 |
+
cur_hidden_states = cur_hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
| 1540 |
+
|
| 1541 |
+
output.append(cur_hidden_states)
|
| 1542 |
+
|
| 1543 |
+
output = output[::-1]
|
| 1544 |
+
else:
|
| 1545 |
+
hidden_states = hidden_states[:, -original_context_length:, :]
|
| 1546 |
+
hidden_states = (self.norm_out.norm(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
|
| 1547 |
+
hidden_states = self.proj_out(hidden_states)
|
| 1548 |
+
hidden_states = hidden_states.reshape(
|
| 1549 |
+
batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
|
| 1550 |
+
)
|
| 1551 |
+
hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
|
| 1552 |
+
output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
| 1553 |
+
|
| 1554 |
+
logits = []
|
| 1555 |
+
if gan_mode and self.is_use_gan:
|
| 1556 |
+
if self.is_use_gan_final:
|
| 1557 |
+
logits.append(self.gradient_checkpointing_method(self.gan_final_head, output))
|
| 1558 |
+
if self.is_use_gan_hooks:
|
| 1559 |
+
for idx, (_, gan_head) in enumerate(self.gan_heads.items()):
|
| 1560 |
+
activation = rearrange(
|
| 1561 |
+
logits_hidden[idx],
|
| 1562 |
+
"b (f h w) c -> b c f h w",
|
| 1563 |
+
f=post_patch_num_frames,
|
| 1564 |
+
h=post_patch_height,
|
| 1565 |
+
w=post_patch_width,
|
| 1566 |
+
)
|
| 1567 |
+
logits.append(self.gradient_checkpointing_method(gan_head, activation.contiguous()))
|
| 1568 |
+
logits = torch.cat(logits, dim=1) if len(logits) > 1 else logits[0]
|
| 1569 |
+
logits_hidden = None
|
| 1570 |
+
del logits_hidden
|
| 1571 |
+
|
| 1572 |
+
if not return_dict:
|
| 1573 |
+
return (output, logits)
|
| 1574 |
+
|
| 1575 |
+
return Transformer2DModelOutput(sample=output, logits=logits)
|
| 1576 |
+
|
| 1577 |
+
def init_weights(self):
|
| 1578 |
+
r"""
|
| 1579 |
+
Initialize model parameters using Xavier initialization.
|
| 1580 |
+
"""
|
| 1581 |
+
|
| 1582 |
+
# basic init
|
| 1583 |
+
for m in self.modules():
|
| 1584 |
+
if isinstance(m, nn.Linear):
|
| 1585 |
+
nn.init.xavier_uniform_(m.weight)
|
| 1586 |
+
if m.bias is not None:
|
| 1587 |
+
nn.init.zeros_(m.bias)
|
| 1588 |
+
|
| 1589 |
+
# init embeddings
|
| 1590 |
+
nn.init.xavier_uniform_(self.patch_embedding.weight.flatten(1))
|
| 1591 |
+
for m in self.condition_embedder.modules():
|
| 1592 |
+
if isinstance(m, nn.Linear):
|
| 1593 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 1594 |
+
|
| 1595 |
+
# init output layer
|
| 1596 |
+
nn.init.zeros_(self.proj_out.weight)
|
| 1597 |
+
|
| 1598 |
+
@classmethod
|
| 1599 |
+
def from_pretrained(
|
| 1600 |
+
cls,
|
| 1601 |
+
pretrained_model_path,
|
| 1602 |
+
subfolder=None,
|
| 1603 |
+
transformer_additional_kwargs={},
|
| 1604 |
+
low_cpu_mem_usage=False,
|
| 1605 |
+
torch_dtype=torch.float32,
|
| 1606 |
+
device_map="cpu",
|
| 1607 |
+
max_workers=8,
|
| 1608 |
+
use_default_loader=False,
|
| 1609 |
+
):
|
| 1610 |
+
if use_default_loader:
|
| 1611 |
+
return super().from_pretrained(
|
| 1612 |
+
pretrained_model_path, subfolder=subfolder, device_map=device_map, torch_dtype=torch_dtype
|
| 1613 |
+
)
|
| 1614 |
+
|
| 1615 |
+
import os
|
| 1616 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 1617 |
+
|
| 1618 |
+
from huggingface_hub import snapshot_download
|
| 1619 |
+
|
| 1620 |
+
from diffusers.utils import WEIGHTS_NAME
|
| 1621 |
+
|
| 1622 |
+
if os.path.exists(pretrained_model_path):
|
| 1623 |
+
if subfolder is not None:
|
| 1624 |
+
pretrained_model_path = os.path.join(pretrained_model_path, subfolder)
|
| 1625 |
+
else:
|
| 1626 |
+
print(f"Downloading from Hugging Face Hub: {pretrained_model_path}")
|
| 1627 |
+
cache_dir = snapshot_download(
|
| 1628 |
+
repo_id=pretrained_model_path,
|
| 1629 |
+
# allow_patterns=["*.json", "*.safetensors", "*.bin"],
|
| 1630 |
+
)
|
| 1631 |
+
pretrained_model_path = cache_dir
|
| 1632 |
+
if subfolder is not None:
|
| 1633 |
+
pretrained_model_path = os.path.join(cache_dir, subfolder)
|
| 1634 |
+
|
| 1635 |
+
print(f"loaded 3D transformer's pretrained weights from {pretrained_model_path} ...")
|
| 1636 |
+
|
| 1637 |
+
config_file = os.path.join(pretrained_model_path, "config.json")
|
| 1638 |
+
if not os.path.isfile(config_file):
|
| 1639 |
+
raise RuntimeError(f"{config_file} does not exist")
|
| 1640 |
+
with open(config_file, "r") as f:
|
| 1641 |
+
config = json.load(f)
|
| 1642 |
+
|
| 1643 |
+
model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)
|
| 1644 |
+
model_file_safetensors = model_file.replace(".bin", ".safetensors")
|
| 1645 |
+
|
| 1646 |
+
if "dict_mapping" in transformer_additional_kwargs.keys():
|
| 1647 |
+
for key in transformer_additional_kwargs["dict_mapping"]:
|
| 1648 |
+
transformer_additional_kwargs[transformer_additional_kwargs["dict_mapping"][key]] = config[key]
|
| 1649 |
+
|
| 1650 |
+
def remap_state_dict_keys(state_dict):
|
| 1651 |
+
"""Remap old key names to new key names for compatibility."""
|
| 1652 |
+
remapped = {}
|
| 1653 |
+
for key, value in state_dict.items():
|
| 1654 |
+
new_key = key
|
| 1655 |
+
# Only remap top-level scale_shift_table, not blocks.*.scale_shift_table
|
| 1656 |
+
if key == "scale_shift_table":
|
| 1657 |
+
new_key = "norm_out.scale_shift_table"
|
| 1658 |
+
print(f"Remapping key: {key} -> {new_key}")
|
| 1659 |
+
remapped[new_key] = value
|
| 1660 |
+
return remapped
|
| 1661 |
+
|
| 1662 |
+
if low_cpu_mem_usage:
|
| 1663 |
+
try:
|
| 1664 |
+
import re
|
| 1665 |
+
|
| 1666 |
+
from diffusers import __version__ as diffusers_version
|
| 1667 |
+
from diffusers.models.model_loading_utils import load_model_dict_into_meta
|
| 1668 |
+
from diffusers.utils import is_accelerate_available
|
| 1669 |
+
|
| 1670 |
+
if is_accelerate_available():
|
| 1671 |
+
import accelerate
|
| 1672 |
+
|
| 1673 |
+
# Instantiate model with empty weights
|
| 1674 |
+
with accelerate.init_empty_weights():
|
| 1675 |
+
model = cls.from_config(config, **transformer_additional_kwargs)
|
| 1676 |
+
|
| 1677 |
+
param_device = "cpu"
|
| 1678 |
+
if os.path.exists(model_file):
|
| 1679 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
| 1680 |
+
elif os.path.exists(model_file_safetensors):
|
| 1681 |
+
from safetensors.torch import load_file
|
| 1682 |
+
|
| 1683 |
+
state_dict = load_file(model_file_safetensors)
|
| 1684 |
+
else:
|
| 1685 |
+
from safetensors.torch import load_file
|
| 1686 |
+
|
| 1687 |
+
model_files_safetensors = glob.glob(os.path.join(pretrained_model_path, "*.safetensors"))
|
| 1688 |
+
state_dict = {}
|
| 1689 |
+
print(f"Loading {len(model_files_safetensors)} safetensors files with {max_workers} workers...")
|
| 1690 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 1691 |
+
future_to_file = {executor.submit(load_file, f): f for f in model_files_safetensors}
|
| 1692 |
+
for future in as_completed(future_to_file):
|
| 1693 |
+
_state_dict = future.result()
|
| 1694 |
+
state_dict.update(_state_dict)
|
| 1695 |
+
|
| 1696 |
+
# Remap keys before loading into meta model
|
| 1697 |
+
state_dict = remap_state_dict_keys(state_dict)
|
| 1698 |
+
|
| 1699 |
+
if diffusers_version >= "0.33.0":
|
| 1700 |
+
# Diffusers has refactored `load_model_dict_into_meta` since version 0.33.0 in this commit:
|
| 1701 |
+
# https://github.com/huggingface/diffusers/commit/f5929e03060d56063ff34b25a8308833bec7c785.
|
| 1702 |
+
load_model_dict_into_meta(
|
| 1703 |
+
model,
|
| 1704 |
+
state_dict,
|
| 1705 |
+
dtype=torch_dtype,
|
| 1706 |
+
model_name_or_path=pretrained_model_path,
|
| 1707 |
+
keep_in_fp32_modules=cls._keep_in_fp32_modules,
|
| 1708 |
+
)
|
| 1709 |
+
else:
|
| 1710 |
+
model._convert_deprecated_attention_blocks(state_dict)
|
| 1711 |
+
# move the params from meta device to cpu
|
| 1712 |
+
missing_keys = set(model.state_dict().keys()) - set(state_dict.keys())
|
| 1713 |
+
if len(missing_keys) > 0:
|
| 1714 |
+
raise ValueError(
|
| 1715 |
+
f"Cannot load {cls} from {pretrained_model_path} because the following keys are"
|
| 1716 |
+
f" missing: \n {', '.join(missing_keys)}. \n Please make sure to pass"
|
| 1717 |
+
" `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize"
|
| 1718 |
+
" those weights or else make sure your checkpoint file is correct."
|
| 1719 |
+
)
|
| 1720 |
+
|
| 1721 |
+
unexpected_keys = load_model_dict_into_meta(
|
| 1722 |
+
model,
|
| 1723 |
+
state_dict,
|
| 1724 |
+
device=param_device,
|
| 1725 |
+
dtype=torch_dtype,
|
| 1726 |
+
model_name_or_path=pretrained_model_path,
|
| 1727 |
+
)
|
| 1728 |
+
|
| 1729 |
+
if cls._keys_to_ignore_on_load_unexpected is not None:
|
| 1730 |
+
for pat in cls._keys_to_ignore_on_load_unexpected:
|
| 1731 |
+
unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
|
| 1732 |
+
|
| 1733 |
+
if len(unexpected_keys) > 0:
|
| 1734 |
+
print(
|
| 1735 |
+
f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}"
|
| 1736 |
+
)
|
| 1737 |
+
|
| 1738 |
+
return model
|
| 1739 |
+
except Exception as e:
|
| 1740 |
+
print(f"The low_cpu_mem_usage mode is not work because {e}. Use low_cpu_mem_usage=False instead.")
|
| 1741 |
+
|
| 1742 |
+
model = cls.from_config(config, **transformer_additional_kwargs)
|
| 1743 |
+
if os.path.exists(model_file):
|
| 1744 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
| 1745 |
+
elif os.path.exists(model_file_safetensors):
|
| 1746 |
+
from safetensors.torch import load_file
|
| 1747 |
+
|
| 1748 |
+
state_dict = load_file(model_file_safetensors)
|
| 1749 |
+
else:
|
| 1750 |
+
from safetensors.torch import load_file
|
| 1751 |
+
|
| 1752 |
+
model_files_safetensors = glob.glob(os.path.join(pretrained_model_path, "*.safetensors"))
|
| 1753 |
+
state_dict = {}
|
| 1754 |
+
print(f"Loading {len(model_files_safetensors)} safetensors files with {max_workers} workers...")
|
| 1755 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 1756 |
+
future_to_file = {executor.submit(load_file, f): f for f in model_files_safetensors}
|
| 1757 |
+
for future in as_completed(future_to_file):
|
| 1758 |
+
_state_dict = future.result()
|
| 1759 |
+
state_dict.update(_state_dict)
|
| 1760 |
+
|
| 1761 |
+
# Remap keys before size check and loading
|
| 1762 |
+
state_dict = remap_state_dict_keys(state_dict)
|
| 1763 |
+
|
| 1764 |
+
tmp_state_dict = {}
|
| 1765 |
+
for key in state_dict:
|
| 1766 |
+
if key in model.state_dict().keys() and model.state_dict()[key].size() == state_dict[key].size():
|
| 1767 |
+
tmp_state_dict[key] = state_dict[key]
|
| 1768 |
+
else:
|
| 1769 |
+
print(key, "Size don't match, skip")
|
| 1770 |
+
|
| 1771 |
+
state_dict = tmp_state_dict
|
| 1772 |
+
|
| 1773 |
+
m, u = model.load_state_dict(state_dict, strict=False)
|
| 1774 |
+
print(f"### missing keys: {len(m)}; \n### unexpected keys: {len(u)};")
|
| 1775 |
+
print(m)
|
| 1776 |
+
|
| 1777 |
+
for name, param in model.named_parameters():
|
| 1778 |
+
should_keep_fp32 = any(pattern in name for pattern in cls._keep_in_fp32_modules)
|
| 1779 |
+
if should_keep_fp32:
|
| 1780 |
+
param.data = param.data.to(torch.float32)
|
| 1781 |
+
# print(f"Keeping parameter {name} in fp32")
|
| 1782 |
+
else:
|
| 1783 |
+
param.data = param.data.to(torch_dtype)
|
| 1784 |
+
model = model.to(device_map)
|
| 1785 |
+
|
| 1786 |
+
params = [p.numel() if "." in n else 0 for n, p in model.named_parameters()]
|
| 1787 |
+
print(f"### All Parameters: {sum(params) / 1e6} M")
|
| 1788 |
+
|
| 1789 |
+
params = [p.numel() if "attn1." in n else 0 for n, p in model.named_parameters()]
|
| 1790 |
+
print(f"### attn1 Parameters: {sum(params) / 1e6} M")
|
| 1791 |
+
|
| 1792 |
+
params = [p.numel() if "attn2." in n else 0 for n, p in model.named_parameters()]
|
| 1793 |
+
print(f"### attn2 Parameters: {sum(params) / 1e6} M")
|
| 1794 |
+
|
| 1795 |
+
return model
|
| 1796 |
+
|
| 1797 |
+
|
| 1798 |
+
if __name__ == "__main__":
|
| 1799 |
+
import os
|
| 1800 |
+
|
| 1801 |
+
os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
|
| 1802 |
+
os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes"
|
| 1803 |
+
# export DIFFUSERS_ENABLE_HUB_KERNELS=yes
|
| 1804 |
+
|
| 1805 |
+
# def compare_models(model1, model2):
|
| 1806 |
+
# for (name1, param1), (name2, param2) in zip(model1.named_parameters(), model2.named_parameters()):
|
| 1807 |
+
# if name1 != name2:
|
| 1808 |
+
# print(f"参数名不同: {name1} vs {name2}")
|
| 1809 |
+
# return False
|
| 1810 |
+
# if not torch.equal(param1, param2):
|
| 1811 |
+
# print(f"参数 {name1} 的值不同")
|
| 1812 |
+
# print(f"最大差异: {torch.max(torch.abs(param1 - param2))}")
|
| 1813 |
+
# return False
|
| 1814 |
+
# print("所有参数完全相同!")
|
| 1815 |
+
# return True
|
| 1816 |
+
# compare_models(transformer, transformer1)
|
| 1817 |
+
|
| 1818 |
+
gan_mode = False
|
| 1819 |
+
is_use_gan_hooks = False
|
| 1820 |
+
transformer_additional_kwargs = {
|
| 1821 |
+
"has_multi_term_memory_patch": True,
|
| 1822 |
+
"zero_history_timestep": True,
|
| 1823 |
+
"guidance_cross_attn": True,
|
| 1824 |
+
"restrict_self_attn": False,
|
| 1825 |
+
"restrict_lora": False,
|
| 1826 |
+
"is_train_restrict_lora": False,
|
| 1827 |
+
"is_amplify_history": False,
|
| 1828 |
+
"history_scale_mode": "per_head", # [scalar, per_head]
|
| 1829 |
+
"is_use_gan": gan_mode,
|
| 1830 |
+
"is_use_gan_hooks": is_use_gan_hooks,
|
| 1831 |
+
"gan_hooks": [13, 21, 29],
|
| 1832 |
+
"gan_cond_map_dim": 768,
|
| 1833 |
+
# "gan_hooks": [10, 20, 30],
|
| 1834 |
+
# "gan_cond_map_dim": 512,
|
| 1835 |
+
}
|
| 1836 |
+
# transformer_additional_kwargs={}
|
| 1837 |
+
|
| 1838 |
+
device = "cuda"
|
| 1839 |
+
weight_dtype = torch.bfloat16
|
| 1840 |
+
transformer = HeliosTransformer3DModel.from_pretrained(
|
| 1841 |
+
"Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
| 1842 |
+
subfolder="transformer",
|
| 1843 |
+
torch_dtype=torch.bfloat16,
|
| 1844 |
+
transformer_additional_kwargs=transformer_additional_kwargs,
|
| 1845 |
+
)
|
| 1846 |
+
transformer.requires_grad_(False)
|
| 1847 |
+
transformer.eval()
|
| 1848 |
+
transformer = transformer.to(device, dtype=weight_dtype)
|
| 1849 |
+
|
| 1850 |
+
# import sys
|
| 1851 |
+
# from argparse import Namespace
|
| 1852 |
+
# sys.path.append("../../")
|
| 1853 |
+
# from helios.utils.utils_helios_base import save_extra_components, load_extra_components
|
| 1854 |
+
# args = Namespace()
|
| 1855 |
+
# args.training_config = Namespace()
|
| 1856 |
+
# args.training_config.is_enable_stage1 = True
|
| 1857 |
+
# args.training_config.is_train_restrict_lora = True
|
| 1858 |
+
# save_extra_components(args, transformer, "./temp")
|
| 1859 |
+
# load_extra_components(args, transformer, "./temp/transformer_partial.pth")
|
| 1860 |
+
|
| 1861 |
+
is_navit = False
|
| 1862 |
+
batch_size = 4
|
| 1863 |
+
max_length = 512
|
| 1864 |
+
if is_navit:
|
| 1865 |
+
noisy_model_input = [
|
| 1866 |
+
torch.randn(batch_size, 16, 9, 12, 20),
|
| 1867 |
+
torch.randn(batch_size, 16, 9, 24, 40),
|
| 1868 |
+
torch.randn(batch_size, 16, 9, 48, 80),
|
| 1869 |
+
]
|
| 1870 |
+
timesteps = [
|
| 1871 |
+
torch.randint(0, 1000, (batch_size,)).to(device),
|
| 1872 |
+
torch.randint(0, 1000, (batch_size,)).to(device),
|
| 1873 |
+
torch.randint(0, 1000, (batch_size,)).to(device),
|
| 1874 |
+
]
|
| 1875 |
+
else:
|
| 1876 |
+
noisy_model_input = torch.randn(batch_size, 16, 9, 48, 80).to(device, dtype=weight_dtype)
|
| 1877 |
+
timesteps = torch.randint(0, 1000, (batch_size,)).to(device)
|
| 1878 |
+
|
| 1879 |
+
prompt_embeds = torch.randn(batch_size, max_length, 4096).to(device, dtype=weight_dtype)
|
| 1880 |
+
indices_hidden_states = torch.randint(0, 10, (batch_size, 9)).to(device)
|
| 1881 |
+
indices_latents_history_short = torch.randint(0, 3, (batch_size, 2)).to(device)
|
| 1882 |
+
indices_latents_history_mid = torch.randint(0, 3, (batch_size, 2)).to(device)
|
| 1883 |
+
indices_latents_history_long = torch.randint(0, 17, (batch_size, 16)).to(device)
|
| 1884 |
+
latents_history_short = torch.randn(batch_size, 16, 2, 48, 80).to(device, dtype=weight_dtype)
|
| 1885 |
+
latents_history_mid = torch.randn(batch_size, 16, 2, 48, 80).to(device, dtype=weight_dtype)
|
| 1886 |
+
latents_history_long = torch.randn(batch_size, 16, 16, 48, 80).to(device, dtype=weight_dtype)
|
| 1887 |
+
|
| 1888 |
+
# 16 2 2: 2400
|
| 1889 |
+
# 16 2 3: 3360
|
| 1890 |
+
# 16 4 2: 2640
|
| 1891 |
+
# 16 4 3: 3600
|
| 1892 |
+
# 8 2 2: 2280
|
| 1893 |
+
# 8 2 3: 3240
|
| 1894 |
+
|
| 1895 |
+
# noisy_model_input_1 = torch.randn(batch_size, 16, 9, 12, 20).to(device, dtype=weight_dtype)
|
| 1896 |
+
# timesteps_1 = torch.randint(0, 1000, (batch_size,)).to(device)
|
| 1897 |
+
# noisy_model_input = [noisy_model_input_1, noisy_model_input_1, noisy_model_input_1]
|
| 1898 |
+
# timesteps = [timesteps_1, timesteps_1, torch.randint(0, 1000, (batch_size,)).to(device)]
|
| 1899 |
+
|
| 1900 |
+
model_pred = transformer(
|
| 1901 |
+
hidden_states=noisy_model_input,
|
| 1902 |
+
timestep=timesteps,
|
| 1903 |
+
encoder_hidden_states=prompt_embeds,
|
| 1904 |
+
indices_hidden_states=indices_hidden_states,
|
| 1905 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1906 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1907 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1908 |
+
latents_history_short=latents_history_short.to(weight_dtype),
|
| 1909 |
+
latents_history_mid=latents_history_mid.to(weight_dtype),
|
| 1910 |
+
latents_history_long=latents_history_long.to(weight_dtype),
|
| 1911 |
+
gan_mode=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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import html
|
| 16 |
+
import math
|
| 17 |
+
from enum import Enum
|
| 18 |
+
from itertools import accumulate
|
| 19 |
+
from typing import Any, Callable, Dict, List, Literal, Optional, Union
|
| 20 |
+
|
| 21 |
+
import regex as re
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from einops import rearrange
|
| 25 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 26 |
+
|
| 27 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 28 |
+
from diffusers.image_processor import PipelineImageInput
|
| 29 |
+
from diffusers.loaders import WanLoraLoaderMixin
|
| 30 |
+
from diffusers.models import AutoencoderKLWan
|
| 31 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 32 |
+
from diffusers.schedulers import UniPCMultistepScheduler
|
| 33 |
+
from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
|
| 34 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 35 |
+
from diffusers.video_processor import VideoProcessor
|
| 36 |
+
|
| 37 |
+
from ..modules.transformer_helios import HeliosTransformer3DModel
|
| 38 |
+
from ..scheduler.scheduling_helios import HeliosScheduler
|
| 39 |
+
from ..utils.utils_base import AdaptiveAntiDrifting, apply_schedule_shift
|
| 40 |
+
from ..utils.utils_helios_post import add_noise, convert_flow_pred_to_x0
|
| 41 |
+
from .pipeline_output import HeliosPipelineOutput
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if is_torch_xla_available():
|
| 45 |
+
import torch_xla.core.xla_model as xm
|
| 46 |
+
|
| 47 |
+
XLA_AVAILABLE = True
|
| 48 |
+
else:
|
| 49 |
+
XLA_AVAILABLE = False
|
| 50 |
+
|
| 51 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 52 |
+
|
| 53 |
+
if is_ftfy_available():
|
| 54 |
+
import ftfy
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
EXAMPLE_DOC_STRING = """
|
| 58 |
+
Examples:
|
| 59 |
+
```python
|
| 60 |
+
>>> import torch
|
| 61 |
+
>>> from diffusers.utils import export_to_video
|
| 62 |
+
>>> from diffusers import AutoencoderKLWan, HeliosPipeline
|
| 63 |
+
|
| 64 |
+
>>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled
|
| 65 |
+
>>> model_id = "BestWishYsh/Helios-Base"
|
| 66 |
+
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 67 |
+
>>> pipe = HeliosPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
|
| 68 |
+
>>> pipe.to("cuda")
|
| 69 |
+
|
| 70 |
+
>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
|
| 71 |
+
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
| 72 |
+
|
| 73 |
+
>>> output = pipe(
|
| 74 |
+
... prompt=prompt,
|
| 75 |
+
... negative_prompt=negative_prompt,
|
| 76 |
+
... height=384,
|
| 77 |
+
... width=640,
|
| 78 |
+
... num_frames=132,
|
| 79 |
+
... guidance_scale=5.0,
|
| 80 |
+
... ).frames[0]
|
| 81 |
+
>>> export_to_video(output, "output.mp4", fps=24)
|
| 82 |
+
```
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@torch.amp.autocast("cuda", dtype=torch.float32)
|
| 87 |
+
def optimized_scale(positive_flat, negative_flat):
|
| 88 |
+
# Calculate dot production
|
| 89 |
+
dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)
|
| 90 |
+
|
| 91 |
+
# Squared norm of uncondition
|
| 92 |
+
squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
|
| 93 |
+
|
| 94 |
+
# st_star = v_cond^T * v_uncond / ||v_uncond||^2
|
| 95 |
+
st_star = dot_product / squared_norm
|
| 96 |
+
|
| 97 |
+
return st_star
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def basic_clean(text):
|
| 101 |
+
text = ftfy.fix_text(text)
|
| 102 |
+
text = html.unescape(html.unescape(text))
|
| 103 |
+
return text.strip()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def whitespace_clean(text):
|
| 107 |
+
text = re.sub(r"\s+", " ", text)
|
| 108 |
+
text = text.strip()
|
| 109 |
+
return text
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def prompt_clean(text):
|
| 113 |
+
text = whitespace_clean(basic_clean(text))
|
| 114 |
+
return text
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class VAEDecodeType(str, Enum):
|
| 118 |
+
DEFAULT = "default"
|
| 119 |
+
DEFAULT_BATCH = "default_batch"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class HeliosPipeline(DiffusionPipeline, WanLoraLoaderMixin):
|
| 123 |
+
r"""
|
| 124 |
+
Pipeline for text-to-video / image-to-video / video-to-video generation using Helios.
|
| 125 |
+
|
| 126 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 127 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
tokenizer ([`T5Tokenizer`]):
|
| 131 |
+
Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
|
| 132 |
+
specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 133 |
+
text_encoder ([`T5EncoderModel`]):
|
| 134 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
| 135 |
+
the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 136 |
+
transformer ([`HeliosTransformer3DModel`]):
|
| 137 |
+
Conditional Transformer to denoise the input latents.
|
| 138 |
+
scheduler ([`UniPCMultistepScheduler`]):
|
| 139 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 140 |
+
vae ([`AutoencoderKLWan`]):
|
| 141 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
| 145 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 146 |
+
_optional_components = ["transformer"]
|
| 147 |
+
|
| 148 |
+
def __init__(
|
| 149 |
+
self,
|
| 150 |
+
tokenizer: AutoTokenizer,
|
| 151 |
+
text_encoder: UMT5EncoderModel,
|
| 152 |
+
vae: AutoencoderKLWan,
|
| 153 |
+
scheduler: UniPCMultistepScheduler | HeliosScheduler,
|
| 154 |
+
transformer: HeliosTransformer3DModel,
|
| 155 |
+
):
|
| 156 |
+
super().__init__()
|
| 157 |
+
|
| 158 |
+
self.register_modules(
|
| 159 |
+
vae=vae,
|
| 160 |
+
text_encoder=text_encoder,
|
| 161 |
+
tokenizer=tokenizer,
|
| 162 |
+
transformer=transformer,
|
| 163 |
+
scheduler=scheduler,
|
| 164 |
+
)
|
| 165 |
+
self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
|
| 166 |
+
self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
|
| 167 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
| 168 |
+
|
| 169 |
+
def _get_t5_prompt_embeds(
|
| 170 |
+
self,
|
| 171 |
+
prompt: Union[str, List[str]] = None,
|
| 172 |
+
num_videos_per_prompt: int = 1,
|
| 173 |
+
max_sequence_length: int = 226,
|
| 174 |
+
device: Optional[torch.device] = None,
|
| 175 |
+
dtype: Optional[torch.dtype] = None,
|
| 176 |
+
):
|
| 177 |
+
device = device or self._execution_device
|
| 178 |
+
dtype = dtype or self.text_encoder.dtype
|
| 179 |
+
|
| 180 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 181 |
+
prompt = [prompt_clean(u) for u in prompt]
|
| 182 |
+
batch_size = len(prompt)
|
| 183 |
+
|
| 184 |
+
text_inputs = self.tokenizer(
|
| 185 |
+
prompt,
|
| 186 |
+
padding="max_length",
|
| 187 |
+
max_length=max_sequence_length,
|
| 188 |
+
truncation=True,
|
| 189 |
+
add_special_tokens=True,
|
| 190 |
+
return_attention_mask=True,
|
| 191 |
+
return_tensors="pt",
|
| 192 |
+
)
|
| 193 |
+
text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
| 194 |
+
seq_lens = mask.gt(0).sum(dim=1).long()
|
| 195 |
+
|
| 196 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
|
| 197 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 198 |
+
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
| 199 |
+
prompt_embeds = torch.stack(
|
| 200 |
+
[torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 204 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 205 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
| 206 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
| 207 |
+
|
| 208 |
+
return prompt_embeds, text_inputs.attention_mask.bool()
|
| 209 |
+
|
| 210 |
+
def encode_prompt(
|
| 211 |
+
self,
|
| 212 |
+
prompt: Union[str, List[str]],
|
| 213 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 214 |
+
do_classifier_free_guidance: bool = True,
|
| 215 |
+
num_videos_per_prompt: int = 1,
|
| 216 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 217 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 218 |
+
max_sequence_length: int = 226,
|
| 219 |
+
device: Optional[torch.device] = None,
|
| 220 |
+
dtype: Optional[torch.dtype] = None,
|
| 221 |
+
):
|
| 222 |
+
r"""
|
| 223 |
+
Encodes the prompt into text encoder hidden states.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 227 |
+
prompt to be encoded
|
| 228 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 229 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 230 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 231 |
+
less than `1`).
|
| 232 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 233 |
+
Whether to use classifier free guidance or not.
|
| 234 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 235 |
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
| 236 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 237 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 238 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 239 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 240 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 241 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 242 |
+
argument.
|
| 243 |
+
device: (`torch.device`, *optional*):
|
| 244 |
+
torch device
|
| 245 |
+
dtype: (`torch.dtype`, *optional*):
|
| 246 |
+
torch dtype
|
| 247 |
+
"""
|
| 248 |
+
device = device or self._execution_device
|
| 249 |
+
|
| 250 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 251 |
+
if prompt is not None:
|
| 252 |
+
batch_size = len(prompt)
|
| 253 |
+
else:
|
| 254 |
+
batch_size = prompt_embeds.shape[0]
|
| 255 |
+
|
| 256 |
+
if prompt_embeds is None:
|
| 257 |
+
prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
|
| 258 |
+
prompt=prompt,
|
| 259 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 260 |
+
max_sequence_length=max_sequence_length,
|
| 261 |
+
device=device,
|
| 262 |
+
dtype=dtype,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
negative_prompt_attention_mask = None
|
| 266 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 267 |
+
negative_prompt = negative_prompt or ""
|
| 268 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
| 269 |
+
|
| 270 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 271 |
+
raise TypeError(
|
| 272 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 273 |
+
f" {type(prompt)}."
|
| 274 |
+
)
|
| 275 |
+
elif batch_size != len(negative_prompt):
|
| 276 |
+
raise ValueError(
|
| 277 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 278 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 279 |
+
" the batch size of `prompt`."
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
negative_prompt_embeds, negative_prompt_attention_mask = self._get_t5_prompt_embeds(
|
| 283 |
+
prompt=negative_prompt,
|
| 284 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 285 |
+
max_sequence_length=max_sequence_length,
|
| 286 |
+
device=device,
|
| 287 |
+
dtype=dtype,
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
|
| 291 |
+
|
| 292 |
+
def check_inputs(
|
| 293 |
+
self,
|
| 294 |
+
prompt,
|
| 295 |
+
negative_prompt,
|
| 296 |
+
height,
|
| 297 |
+
width,
|
| 298 |
+
prompt_embeds=None,
|
| 299 |
+
negative_prompt_embeds=None,
|
| 300 |
+
callback_on_step_end_tensor_inputs=None,
|
| 301 |
+
):
|
| 302 |
+
if height % 16 != 0 or width % 16 != 0:
|
| 303 |
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
| 304 |
+
|
| 305 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 306 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 307 |
+
):
|
| 308 |
+
raise ValueError(
|
| 309 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
if prompt is not None and prompt_embeds is not None:
|
| 313 |
+
raise ValueError(
|
| 314 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 315 |
+
" only forward one of the two."
|
| 316 |
+
)
|
| 317 |
+
elif negative_prompt is not None and negative_prompt_embeds is not None:
|
| 318 |
+
raise ValueError(
|
| 319 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
|
| 320 |
+
" only forward one of the two."
|
| 321 |
+
)
|
| 322 |
+
elif prompt is None and prompt_embeds is None:
|
| 323 |
+
raise ValueError(
|
| 324 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 325 |
+
)
|
| 326 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 327 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 328 |
+
elif negative_prompt is not None and (
|
| 329 |
+
not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
|
| 330 |
+
):
|
| 331 |
+
raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
|
| 332 |
+
|
| 333 |
+
def prepare_latents(
|
| 334 |
+
self,
|
| 335 |
+
batch_size: int,
|
| 336 |
+
num_channels_latents: int = 16,
|
| 337 |
+
height: int = 480,
|
| 338 |
+
width: int = 832,
|
| 339 |
+
num_frames: int = 81,
|
| 340 |
+
dtype: Optional[torch.dtype] = None,
|
| 341 |
+
device: Optional[torch.device] = None,
|
| 342 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 343 |
+
latents: Optional[torch.Tensor] = None,
|
| 344 |
+
) -> torch.Tensor:
|
| 345 |
+
if latents is not None:
|
| 346 |
+
return latents.to(device=device, dtype=dtype)
|
| 347 |
+
|
| 348 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
| 349 |
+
shape = (
|
| 350 |
+
batch_size,
|
| 351 |
+
num_channels_latents,
|
| 352 |
+
num_latent_frames,
|
| 353 |
+
int(height) // self.vae_scale_factor_spatial,
|
| 354 |
+
int(width) // self.vae_scale_factor_spatial,
|
| 355 |
+
)
|
| 356 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 357 |
+
raise ValueError(
|
| 358 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 359 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 363 |
+
return latents
|
| 364 |
+
|
| 365 |
+
def prepare_image_latents(
|
| 366 |
+
self,
|
| 367 |
+
image: torch.Tensor,
|
| 368 |
+
latents_mean: torch.Tensor,
|
| 369 |
+
latents_std: torch.Tensor,
|
| 370 |
+
dtype: Optional[torch.dtype] = None,
|
| 371 |
+
device: Optional[torch.device] = None,
|
| 372 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 373 |
+
latents: Optional[torch.Tensor] = None,
|
| 374 |
+
fake_latents: Optional[torch.Tensor] = None,
|
| 375 |
+
) -> torch.Tensor:
|
| 376 |
+
device = device or self._execution_device
|
| 377 |
+
if latents is None:
|
| 378 |
+
image = image.unsqueeze(2).to(device=device, dtype=self.vae.dtype)
|
| 379 |
+
latents = self.vae.encode(image).latent_dist.sample(generator=generator)
|
| 380 |
+
latents = (latents - latents_mean) * latents_std
|
| 381 |
+
if fake_latents is None:
|
| 382 |
+
fake_video = image.repeat(1, 1, 33, 1, 1).to(device=device, dtype=self.vae.dtype)
|
| 383 |
+
fake_latents_full = self.vae.encode(fake_video).latent_dist.sample(generator=generator)
|
| 384 |
+
fake_latents_full = (fake_latents_full - latents_mean) * latents_std
|
| 385 |
+
fake_latents = fake_latents_full[:, :, -1:, :, :]
|
| 386 |
+
return latents.to(device=device, dtype=dtype), fake_latents.to(device=device, dtype=dtype)
|
| 387 |
+
|
| 388 |
+
def prepare_video_latents(
|
| 389 |
+
self,
|
| 390 |
+
video: torch.Tensor,
|
| 391 |
+
latents_mean: torch.Tensor,
|
| 392 |
+
latents_std: torch.Tensor,
|
| 393 |
+
latent_window_size: int,
|
| 394 |
+
dtype: Optional[torch.dtype] = None,
|
| 395 |
+
device: Optional[torch.device] = None,
|
| 396 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 397 |
+
latents: Optional[torch.Tensor] = None,
|
| 398 |
+
) -> torch.Tensor:
|
| 399 |
+
device = device or self._execution_device
|
| 400 |
+
video = video.to(device=device, dtype=self.vae.dtype)
|
| 401 |
+
if latents is None:
|
| 402 |
+
num_frames = video.shape[2]
|
| 403 |
+
min_frames = (latent_window_size - 1) * 4 + 1
|
| 404 |
+
num_chunks = num_frames // min_frames
|
| 405 |
+
if num_chunks == 0:
|
| 406 |
+
raise ValueError(
|
| 407 |
+
f"Video must have at least {min_frames} frames "
|
| 408 |
+
f"(got {num_frames} frames). "
|
| 409 |
+
f"Required: (latent_window_size - 1) * 4 + 1 = ({latent_window_size} - 1) * 4 + 1 = {min_frames}"
|
| 410 |
+
)
|
| 411 |
+
total_valid_frames = num_chunks * min_frames
|
| 412 |
+
start_frame = num_frames - total_valid_frames
|
| 413 |
+
|
| 414 |
+
first_frame = video[:, :, 0:1, :, :]
|
| 415 |
+
first_frame_latent = self.vae.encode(first_frame).latent_dist.sample(generator=generator)
|
| 416 |
+
first_frame_latent = (first_frame_latent - latents_mean) * latents_std
|
| 417 |
+
|
| 418 |
+
latents_chunks = []
|
| 419 |
+
for i in range(num_chunks - 1, -1, -1):
|
| 420 |
+
chunk_start = start_frame + i * min_frames
|
| 421 |
+
chunk_end = chunk_start + min_frames
|
| 422 |
+
video_chunk = video[:, :, chunk_start:chunk_end, :, :]
|
| 423 |
+
chunk_latents = self.vae.encode(video_chunk).latent_dist.sample(generator=generator)
|
| 424 |
+
chunk_latents = (chunk_latents - latents_mean) * latents_std
|
| 425 |
+
latents_chunks.insert(0, chunk_latents)
|
| 426 |
+
latents = torch.cat(latents_chunks, dim=2)
|
| 427 |
+
return first_frame_latent.to(device=device, dtype=dtype), latents.to(device=device, dtype=dtype)
|
| 428 |
+
|
| 429 |
+
def interpolate_prompt_embeds(
|
| 430 |
+
self,
|
| 431 |
+
prompt_embeds_1: torch.Tensor,
|
| 432 |
+
prompt_embeds_2: torch.Tensor,
|
| 433 |
+
interpolation_steps: int = 4,
|
| 434 |
+
):
|
| 435 |
+
x = torch.lerp(
|
| 436 |
+
prompt_embeds_1,
|
| 437 |
+
prompt_embeds_2,
|
| 438 |
+
torch.linspace(0, 1, steps=interpolation_steps).unsqueeze(1).unsqueeze(2).to(prompt_embeds_1),
|
| 439 |
+
)
|
| 440 |
+
interpolated_prompt_embeds = list(x.chunk(interpolation_steps, dim=0))
|
| 441 |
+
return interpolated_prompt_embeds
|
| 442 |
+
|
| 443 |
+
def sample_block_noise(
|
| 444 |
+
self,
|
| 445 |
+
batch_size,
|
| 446 |
+
channel,
|
| 447 |
+
num_frames,
|
| 448 |
+
height,
|
| 449 |
+
width,
|
| 450 |
+
patch_size: tuple[int, ...] = (1, 2, 2),
|
| 451 |
+
device: torch.device | None = None,
|
| 452 |
+
generator: torch.Generator | None = None,
|
| 453 |
+
):
|
| 454 |
+
# NOTE: A generator must be provided to ensure correct and reproducible results.
|
| 455 |
+
# Creating a default generator here is a fallback only — without a fixed seed,
|
| 456 |
+
# the output will be non-deterministic and may produce incorrect results in CP context.
|
| 457 |
+
if generator is None:
|
| 458 |
+
generator = torch.Generator(device=device)
|
| 459 |
+
elif isinstance(generator, list):
|
| 460 |
+
generator = generator[0]
|
| 461 |
+
|
| 462 |
+
gamma = self.scheduler.config.gamma
|
| 463 |
+
_, ph, pw = patch_size
|
| 464 |
+
block_size = ph * pw
|
| 465 |
+
|
| 466 |
+
cov = (
|
| 467 |
+
torch.eye(block_size, device=device) * (1 + gamma)
|
| 468 |
+
- torch.ones(block_size, block_size, device=device) * gamma
|
| 469 |
+
)
|
| 470 |
+
cov += torch.eye(block_size, device=device) * 1e-8
|
| 471 |
+
cov = cov.float() # Upcast to fp32 for numerical stability — cholesky is unreliable in fp16/bf16.
|
| 472 |
+
|
| 473 |
+
L = torch.linalg.cholesky(cov)
|
| 474 |
+
block_number = batch_size * channel * num_frames * (height // ph) * (width // pw)
|
| 475 |
+
z = torch.randn(block_number, block_size, generator=generator, device=generator.device).to(device=device)
|
| 476 |
+
noise = z @ L.T
|
| 477 |
+
|
| 478 |
+
noise = noise.view(batch_size, channel, num_frames, height // ph, width // pw, ph, pw)
|
| 479 |
+
noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(batch_size, channel, num_frames, height, width)
|
| 480 |
+
|
| 481 |
+
return noise
|
| 482 |
+
|
| 483 |
+
def stage1_sample(
|
| 484 |
+
self,
|
| 485 |
+
latents: torch.Tensor = None,
|
| 486 |
+
prompt_embeds: torch.Tensor = None,
|
| 487 |
+
negative_prompt_embeds: torch.Tensor = None,
|
| 488 |
+
timesteps: torch.Tensor = None,
|
| 489 |
+
guidance_scale: Optional[float] = 5.0,
|
| 490 |
+
indices_hidden_states: torch.Tensor = None,
|
| 491 |
+
indices_latents_history_short: torch.Tensor = None,
|
| 492 |
+
indices_latents_history_mid: torch.Tensor = None,
|
| 493 |
+
indices_latents_history_long: torch.Tensor = None,
|
| 494 |
+
latents_history_short: torch.Tensor = None,
|
| 495 |
+
latents_history_mid: torch.Tensor = None,
|
| 496 |
+
latents_history_long: torch.Tensor = None,
|
| 497 |
+
attention_kwargs: Optional[dict] = None,
|
| 498 |
+
device: Optional[torch.device] = None,
|
| 499 |
+
transformer_dtype: torch.dtype = None,
|
| 500 |
+
generator: Optional[torch.Generator] = None,
|
| 501 |
+
# ------------ CFG Zero ------------
|
| 502 |
+
use_cfg_zero_star: Optional[bool] = False,
|
| 503 |
+
use_zero_init: Optional[bool] = True,
|
| 504 |
+
zero_steps: Optional[int] = 1,
|
| 505 |
+
# -------------- DMD --------------
|
| 506 |
+
use_dmd: bool = False,
|
| 507 |
+
dmd_sigmas: torch.Tensor = None,
|
| 508 |
+
dmd_timesteps: torch.Tensor = None,
|
| 509 |
+
is_amplify_first_chunk: bool = False,
|
| 510 |
+
# ------------ Callback ------------
|
| 511 |
+
callback_on_step_end: Optional[callable] = None,
|
| 512 |
+
callback_on_step_end_tensor_inputs: list = None,
|
| 513 |
+
progress_bar=None,
|
| 514 |
+
):
|
| 515 |
+
batch_size = latents.shape[0]
|
| 516 |
+
|
| 517 |
+
for i, t in enumerate(timesteps):
|
| 518 |
+
is_first_step = i == 0
|
| 519 |
+
|
| 520 |
+
if self.interrupt:
|
| 521 |
+
continue
|
| 522 |
+
|
| 523 |
+
self._current_timestep = t
|
| 524 |
+
timestep = t.expand(latents.shape[0])
|
| 525 |
+
|
| 526 |
+
latent_model_input = latents.to(transformer_dtype)
|
| 527 |
+
with self.transformer.cache_context("cond"):
|
| 528 |
+
noise_pred = self.transformer(
|
| 529 |
+
hidden_states=latent_model_input,
|
| 530 |
+
timestep=timestep,
|
| 531 |
+
encoder_hidden_states=prompt_embeds,
|
| 532 |
+
indices_hidden_states=indices_hidden_states,
|
| 533 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 534 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 535 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 536 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 537 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 538 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 539 |
+
is_first_denoising_step=is_first_step,
|
| 540 |
+
attention_kwargs=attention_kwargs,
|
| 541 |
+
return_dict=False,
|
| 542 |
+
)[0]
|
| 543 |
+
|
| 544 |
+
if self.do_classifier_free_guidance and not use_dmd:
|
| 545 |
+
with self.transformer.cache_context("uncond"):
|
| 546 |
+
noise_uncond = self.transformer(
|
| 547 |
+
hidden_states=latent_model_input,
|
| 548 |
+
timestep=timestep,
|
| 549 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 550 |
+
indices_hidden_states=indices_hidden_states,
|
| 551 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 552 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 553 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 554 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 555 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 556 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 557 |
+
is_first_denoising_step=is_first_step,
|
| 558 |
+
attention_kwargs=attention_kwargs,
|
| 559 |
+
return_dict=False,
|
| 560 |
+
)[0]
|
| 561 |
+
|
| 562 |
+
if use_cfg_zero_star:
|
| 563 |
+
noise_pred_text = noise_pred
|
| 564 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 565 |
+
negative_flat = noise_uncond.view(batch_size, -1)
|
| 566 |
+
|
| 567 |
+
alpha = optimized_scale(positive_flat, negative_flat)
|
| 568 |
+
alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
|
| 569 |
+
alpha = alpha.to(noise_pred_text.dtype)
|
| 570 |
+
|
| 571 |
+
if (i <= zero_steps) and use_zero_init:
|
| 572 |
+
noise_pred = noise_pred_text * 0.0
|
| 573 |
+
else:
|
| 574 |
+
noise_pred = noise_uncond * alpha + guidance_scale * (noise_pred_text - noise_uncond * alpha)
|
| 575 |
+
else:
|
| 576 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
| 577 |
+
|
| 578 |
+
if use_dmd:
|
| 579 |
+
pred_image_or_video = convert_flow_pred_to_x0(
|
| 580 |
+
flow_pred=noise_pred,
|
| 581 |
+
xt=latent_model_input,
|
| 582 |
+
timestep=t * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device),
|
| 583 |
+
sigmas=dmd_sigmas,
|
| 584 |
+
timesteps=dmd_timesteps,
|
| 585 |
+
)
|
| 586 |
+
if i < len(timesteps) - 1:
|
| 587 |
+
latents = add_noise(
|
| 588 |
+
pred_image_or_video,
|
| 589 |
+
randn_tensor(pred_image_or_video.shape, generator=generator, device=device),
|
| 590 |
+
timesteps[i + 1] * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device),
|
| 591 |
+
sigmas=dmd_sigmas,
|
| 592 |
+
timesteps=dmd_timesteps,
|
| 593 |
+
)
|
| 594 |
+
else:
|
| 595 |
+
latents = pred_image_or_video
|
| 596 |
+
else:
|
| 597 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 598 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 599 |
+
|
| 600 |
+
if callback_on_step_end is not None:
|
| 601 |
+
callback_kwargs = {}
|
| 602 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 603 |
+
callback_kwargs[k] = locals()[k]
|
| 604 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 605 |
+
|
| 606 |
+
latents = callback_outputs.pop("latents", latents)
|
| 607 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 608 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 609 |
+
|
| 610 |
+
progress_bar.update()
|
| 611 |
+
|
| 612 |
+
if XLA_AVAILABLE:
|
| 613 |
+
xm.mark_step()
|
| 614 |
+
|
| 615 |
+
return latents
|
| 616 |
+
|
| 617 |
+
def stage2_sample(
|
| 618 |
+
self,
|
| 619 |
+
latents: torch.Tensor = None,
|
| 620 |
+
stage2_num_stages: int = None,
|
| 621 |
+
stage2_num_inference_steps_list: List[int] = None,
|
| 622 |
+
prompt_embeds: torch.Tensor = None,
|
| 623 |
+
negative_prompt_embeds: torch.Tensor = None,
|
| 624 |
+
guidance_scale: Optional[float] = 5.0,
|
| 625 |
+
indices_hidden_states: torch.Tensor = None,
|
| 626 |
+
indices_latents_history_short: torch.Tensor = None,
|
| 627 |
+
indices_latents_history_mid: torch.Tensor = None,
|
| 628 |
+
indices_latents_history_long: torch.Tensor = None,
|
| 629 |
+
latents_history_short: torch.Tensor = None,
|
| 630 |
+
latents_history_mid: torch.Tensor = None,
|
| 631 |
+
latents_history_long: torch.Tensor = None,
|
| 632 |
+
attention_kwargs: Optional[dict] = None,
|
| 633 |
+
device: Optional[torch.device] = None,
|
| 634 |
+
transformer_dtype: torch.dtype = None,
|
| 635 |
+
scheduler_type: str = "unipc", # unipc, euler
|
| 636 |
+
use_dynamic_shifting: bool = False,
|
| 637 |
+
time_shift_type: Literal["exponential", "linear"] = "linear",
|
| 638 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 639 |
+
# ------------ CFG Zero ------------
|
| 640 |
+
use_cfg_zero_star: Optional[bool] = False,
|
| 641 |
+
use_zero_init: Optional[bool] = True,
|
| 642 |
+
zero_steps: Optional[int] = 1,
|
| 643 |
+
# -------------- DMD --------------
|
| 644 |
+
use_dmd: bool = False,
|
| 645 |
+
is_amplify_first_chunk: bool = False,
|
| 646 |
+
# ------------ Callback ------------
|
| 647 |
+
callback_on_step_end: Optional[callable] = None,
|
| 648 |
+
callback_on_step_end_tensor_inputs: list = None,
|
| 649 |
+
progress_bar=None,
|
| 650 |
+
):
|
| 651 |
+
num_frames, height, width = (
|
| 652 |
+
latents.shape[-3],
|
| 653 |
+
latents.shape[-2],
|
| 654 |
+
latents.shape[-1],
|
| 655 |
+
)
|
| 656 |
+
latents = rearrange(latents, "b c t h w -> (b t) c h w")
|
| 657 |
+
for _ in range(stage2_num_stages - 1):
|
| 658 |
+
height //= 2
|
| 659 |
+
width //= 2
|
| 660 |
+
latents = (
|
| 661 |
+
F.interpolate(
|
| 662 |
+
latents,
|
| 663 |
+
size=(height, width),
|
| 664 |
+
mode="bilinear",
|
| 665 |
+
)
|
| 666 |
+
* 2
|
| 667 |
+
)
|
| 668 |
+
latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames)
|
| 669 |
+
|
| 670 |
+
batch_size = latents.shape[0]
|
| 671 |
+
if use_dmd:
|
| 672 |
+
start_point_list = [latents]
|
| 673 |
+
|
| 674 |
+
i = 0
|
| 675 |
+
for i_s in range(stage2_num_stages):
|
| 676 |
+
if use_dmd:
|
| 677 |
+
if is_amplify_first_chunk:
|
| 678 |
+
self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s] * 2 + 1, i_s, device=device)
|
| 679 |
+
else:
|
| 680 |
+
self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s] + 1, i_s, device=device)
|
| 681 |
+
self.scheduler.timesteps = self.scheduler.timesteps[:-1]
|
| 682 |
+
self.scheduler.sigmas = torch.cat([self.scheduler.sigmas[:-2], self.scheduler.sigmas[-1:]])
|
| 683 |
+
else:
|
| 684 |
+
self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s, device=device)
|
| 685 |
+
|
| 686 |
+
if i_s > 0:
|
| 687 |
+
height *= 2
|
| 688 |
+
width *= 2
|
| 689 |
+
num_frames = latents.shape[2]
|
| 690 |
+
latents = rearrange(latents, "b c t h w -> (b t) c h w")
|
| 691 |
+
latents = F.interpolate(latents, size=(height, width), mode="nearest")
|
| 692 |
+
latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames)
|
| 693 |
+
# Fix the stage
|
| 694 |
+
ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal
|
| 695 |
+
gamma = self.scheduler.config.gamma
|
| 696 |
+
alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)
|
| 697 |
+
beta = alpha * (1 - ori_sigma) / math.sqrt(gamma)
|
| 698 |
+
|
| 699 |
+
batch_size, channel, num_frames, height, width = latents.shape
|
| 700 |
+
noise = self.sample_block_noise(
|
| 701 |
+
batch_size,
|
| 702 |
+
channel,
|
| 703 |
+
num_frames,
|
| 704 |
+
height,
|
| 705 |
+
width,
|
| 706 |
+
self.transformer.config.patch_size,
|
| 707 |
+
device,
|
| 708 |
+
generator,
|
| 709 |
+
)
|
| 710 |
+
noise = noise.to(device=device, dtype=transformer_dtype)
|
| 711 |
+
latents = alpha * latents + beta * noise # To fix the block artifact
|
| 712 |
+
|
| 713 |
+
if use_dmd:
|
| 714 |
+
start_point_list.append(latents)
|
| 715 |
+
|
| 716 |
+
if use_dynamic_shifting:
|
| 717 |
+
temp_sigmas = apply_schedule_shift(
|
| 718 |
+
self.scheduler.sigmas,
|
| 719 |
+
latents,
|
| 720 |
+
base_seq_len=self.scheduler.config.get("base_image_seq_len", 256),
|
| 721 |
+
max_seq_len=self.scheduler.config.get("max_image_seq_len", 4096),
|
| 722 |
+
base_shift=self.scheduler.config.get("base_shift", 0.5),
|
| 723 |
+
max_shift=self.scheduler.config.get("max_shift", 1.15),
|
| 724 |
+
time_shift_type=time_shift_type,
|
| 725 |
+
)
|
| 726 |
+
temp_timesteps = self.scheduler.timesteps_per_stage[i_s].min() + temp_sigmas[:-1] * (
|
| 727 |
+
self.scheduler.timesteps_per_stage[i_s].max() - self.scheduler.timesteps_per_stage[i_s].min()
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
self.scheduler.sigmas = temp_sigmas
|
| 731 |
+
self.scheduler.timesteps = temp_timesteps
|
| 732 |
+
|
| 733 |
+
timesteps = self.scheduler.timesteps
|
| 734 |
+
|
| 735 |
+
for idx, t in enumerate(timesteps):
|
| 736 |
+
is_first_step = i_s == 0 and idx == 0
|
| 737 |
+
|
| 738 |
+
timestep = t.expand(latents.shape[0]).to(torch.int64)
|
| 739 |
+
|
| 740 |
+
with self.transformer.cache_context("cond"):
|
| 741 |
+
noise_pred = self.transformer(
|
| 742 |
+
hidden_states=latents.to(transformer_dtype),
|
| 743 |
+
timestep=timestep,
|
| 744 |
+
encoder_hidden_states=prompt_embeds,
|
| 745 |
+
attention_kwargs=attention_kwargs,
|
| 746 |
+
return_dict=False,
|
| 747 |
+
indices_hidden_states=indices_hidden_states,
|
| 748 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 749 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 750 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 751 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 752 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 753 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 754 |
+
is_first_denoising_step=is_first_step,
|
| 755 |
+
)[0]
|
| 756 |
+
|
| 757 |
+
if self.do_classifier_free_guidance:
|
| 758 |
+
with self.transformer.cache_context("cond_uncond"):
|
| 759 |
+
noise_uncond = self.transformer(
|
| 760 |
+
hidden_states=latents.to(transformer_dtype),
|
| 761 |
+
timestep=timestep,
|
| 762 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 763 |
+
attention_kwargs=attention_kwargs,
|
| 764 |
+
return_dict=False,
|
| 765 |
+
indices_hidden_states=indices_hidden_states,
|
| 766 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 767 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 768 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 769 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 770 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 771 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 772 |
+
is_first_denoising_step=is_first_step,
|
| 773 |
+
)[0]
|
| 774 |
+
|
| 775 |
+
if use_cfg_zero_star:
|
| 776 |
+
noise_pred_text = noise_pred
|
| 777 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 778 |
+
negative_flat = noise_uncond.view(batch_size, -1)
|
| 779 |
+
|
| 780 |
+
alpha = optimized_scale(positive_flat, negative_flat)
|
| 781 |
+
alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
|
| 782 |
+
alpha = alpha.to(noise_pred_text.dtype)
|
| 783 |
+
|
| 784 |
+
if (i_s == 0 and idx <= zero_steps) and use_zero_init:
|
| 785 |
+
noise_pred = noise_pred_text * 0.0
|
| 786 |
+
else:
|
| 787 |
+
noise_pred = noise_uncond * alpha + guidance_scale * (
|
| 788 |
+
noise_pred_text - noise_uncond * alpha
|
| 789 |
+
)
|
| 790 |
+
else:
|
| 791 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
| 792 |
+
|
| 793 |
+
if use_dmd:
|
| 794 |
+
pred_image_or_video = convert_flow_pred_to_x0(
|
| 795 |
+
flow_pred=noise_pred,
|
| 796 |
+
xt=latents,
|
| 797 |
+
timestep=timestep,
|
| 798 |
+
sigmas=self.scheduler.sigmas,
|
| 799 |
+
timesteps=self.scheduler.timesteps,
|
| 800 |
+
)
|
| 801 |
+
if idx < len(timesteps) - 1:
|
| 802 |
+
latents = add_noise(
|
| 803 |
+
pred_image_or_video,
|
| 804 |
+
start_point_list[i_s],
|
| 805 |
+
timesteps[idx + 1] * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device),
|
| 806 |
+
sigmas=self.scheduler.sigmas,
|
| 807 |
+
timesteps=self.scheduler.timesteps,
|
| 808 |
+
)
|
| 809 |
+
else:
|
| 810 |
+
latents = pred_image_or_video
|
| 811 |
+
else:
|
| 812 |
+
if scheduler_type == "unipc":
|
| 813 |
+
latents = self.scheduler.step_unipc(noise_pred.float(), t, latents, return_dict=False)[0]
|
| 814 |
+
else:
|
| 815 |
+
latents = self.scheduler.step(noise_pred.float(), t, latents, return_dict=False)[0]
|
| 816 |
+
|
| 817 |
+
if callback_on_step_end is not None:
|
| 818 |
+
callback_kwargs = {}
|
| 819 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 820 |
+
callback_kwargs[k] = locals()[k]
|
| 821 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 822 |
+
|
| 823 |
+
latents = callback_outputs.pop("latents", latents)
|
| 824 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 825 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 826 |
+
|
| 827 |
+
progress_bar.update()
|
| 828 |
+
|
| 829 |
+
if XLA_AVAILABLE:
|
| 830 |
+
xm.mark_step()
|
| 831 |
+
|
| 832 |
+
i += 1
|
| 833 |
+
|
| 834 |
+
return latents
|
| 835 |
+
|
| 836 |
+
@property
|
| 837 |
+
def guidance_scale(self):
|
| 838 |
+
return self._guidance_scale
|
| 839 |
+
|
| 840 |
+
@property
|
| 841 |
+
def do_classifier_free_guidance(self):
|
| 842 |
+
return self._guidance_scale > 1.0
|
| 843 |
+
|
| 844 |
+
@property
|
| 845 |
+
def num_timesteps(self):
|
| 846 |
+
return self._num_timesteps
|
| 847 |
+
|
| 848 |
+
@property
|
| 849 |
+
def current_timestep(self):
|
| 850 |
+
return self._current_timestep
|
| 851 |
+
|
| 852 |
+
@property
|
| 853 |
+
def interrupt(self):
|
| 854 |
+
return self._interrupt
|
| 855 |
+
|
| 856 |
+
@property
|
| 857 |
+
def attention_kwargs(self):
|
| 858 |
+
return self._attention_kwargs
|
| 859 |
+
|
| 860 |
+
@torch.no_grad()
|
| 861 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 862 |
+
def __call__(
|
| 863 |
+
self,
|
| 864 |
+
prompt: Union[str, List[str]] = None,
|
| 865 |
+
negative_prompt: Union[str, List[str]] = None,
|
| 866 |
+
height: int = 384,
|
| 867 |
+
width: int = 640,
|
| 868 |
+
num_frames: int = 73,
|
| 869 |
+
num_inference_steps: int = 50,
|
| 870 |
+
guidance_scale: float = 5.0,
|
| 871 |
+
num_videos_per_prompt: Optional[int] = 1,
|
| 872 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 873 |
+
latents: Optional[torch.Tensor] = None,
|
| 874 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 875 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 876 |
+
output_type: Optional[str] = "np",
|
| 877 |
+
return_dict: bool = True,
|
| 878 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 879 |
+
callback_on_step_end: Optional[
|
| 880 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
| 881 |
+
] = None,
|
| 882 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 883 |
+
max_sequence_length: int = 512,
|
| 884 |
+
# ------------ I2V ------------
|
| 885 |
+
image: Optional[PipelineImageInput] = None,
|
| 886 |
+
image_latents: Optional[torch.Tensor] = None,
|
| 887 |
+
fake_image_latents: Optional[torch.Tensor] = None,
|
| 888 |
+
add_noise_to_image_latents: bool = True,
|
| 889 |
+
image_noise_sigma_min: float = 0.111,
|
| 890 |
+
image_noise_sigma_max: float = 0.135,
|
| 891 |
+
# ------------ V2V ------------
|
| 892 |
+
video: Optional[PipelineImageInput] = None,
|
| 893 |
+
video_latents: Optional[torch.Tensor] = None,
|
| 894 |
+
add_noise_to_video_latents: bool = True,
|
| 895 |
+
video_noise_sigma_min: float = 0.111,
|
| 896 |
+
video_noise_sigma_max: float = 0.135,
|
| 897 |
+
# ------------ Interactive ------------
|
| 898 |
+
use_interpolate_prompt: bool = False,
|
| 899 |
+
interpolate_time_list: list = [7, 7, 7],
|
| 900 |
+
interpolation_steps: int = 3,
|
| 901 |
+
# ------------ Stage 1 ------------
|
| 902 |
+
history_sizes: list = [16, 2, 1],
|
| 903 |
+
latent_window_size: int = 9,
|
| 904 |
+
use_dynamic_shifting: bool = False,
|
| 905 |
+
time_shift_type: Literal["exponential", "linear"] = "linear",
|
| 906 |
+
is_keep_x0: bool = True,
|
| 907 |
+
# ------------ Stage 2 ------------
|
| 908 |
+
is_enable_stage2: bool = False,
|
| 909 |
+
stage2_num_stages: int = 3,
|
| 910 |
+
stage2_num_inference_steps_list: list = [10, 10, 10],
|
| 911 |
+
scheduler_type: str = "unipc", # unipc, euler
|
| 912 |
+
# ------------ CFG Zero ------------
|
| 913 |
+
use_cfg_zero_star: Optional[bool] = False,
|
| 914 |
+
use_zero_init: Optional[bool] = True,
|
| 915 |
+
zero_steps: Optional[int] = 1,
|
| 916 |
+
# ------------ DMD ------------
|
| 917 |
+
use_dmd: bool = False,
|
| 918 |
+
is_skip_first_section: bool = False,
|
| 919 |
+
is_amplify_first_chunk: bool = False,
|
| 920 |
+
# ------------ Adaptive Anti-Drifting ------------
|
| 921 |
+
use_adaptive_anti_drifting: bool = False,
|
| 922 |
+
anti_drift_rho_mu: float = 0.9,
|
| 923 |
+
anti_drift_rho_sigma: float = 0.9,
|
| 924 |
+
anti_drift_delta_mu: float = 0.15,
|
| 925 |
+
anti_drift_delta_sigma: float = 0.15,
|
| 926 |
+
anti_drift_corruption_strength: float = 0.1,
|
| 927 |
+
# ------------ other ------------
|
| 928 |
+
use_kv_cache: bool = False,
|
| 929 |
+
vae_decode_type: VAEDecodeType = "default", # "default", "default_batch"
|
| 930 |
+
):
|
| 931 |
+
r"""
|
| 932 |
+
The call function to the pipeline for generation.
|
| 933 |
+
|
| 934 |
+
Args:
|
| 935 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 936 |
+
The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
|
| 937 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 938 |
+
The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
|
| 939 |
+
instead. Ignored when not using guidance (`guidance_scale` < `1`).
|
| 940 |
+
height (`int`, defaults to `480`):
|
| 941 |
+
The height in pixels of the generated image.
|
| 942 |
+
width (`int`, defaults to `832`):
|
| 943 |
+
The width in pixels of the generated image.
|
| 944 |
+
num_frames (`int`, defaults to `81`):
|
| 945 |
+
The number of frames in the generated video.
|
| 946 |
+
num_inference_steps (`int`, defaults to `50`):
|
| 947 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 948 |
+
expense of slower inference.
|
| 949 |
+
guidance_scale (`float`, defaults to `5.0`):
|
| 950 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
| 951 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
| 952 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
| 953 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
| 954 |
+
the text `prompt`, usually at the expense of lower image quality.
|
| 955 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 956 |
+
The number of images to generate per prompt.
|
| 957 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 958 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 959 |
+
generation deterministic.
|
| 960 |
+
latents (`torch.Tensor`, *optional*):
|
| 961 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 962 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 963 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 964 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 965 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 966 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 967 |
+
output_type (`str`, *optional*, defaults to `"np"`):
|
| 968 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 969 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 970 |
+
Whether or not to return a [`HeliosPipelineOutput`] instead of a plain tuple.
|
| 971 |
+
attention_kwargs (`dict`, *optional*):
|
| 972 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 973 |
+
`self.processor` in
|
| 974 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 975 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
| 976 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
| 977 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
| 978 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
| 979 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
| 980 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 981 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 982 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 983 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 984 |
+
max_sequence_length (`int`, defaults to `512`):
|
| 985 |
+
The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
|
| 986 |
+
truncated. If the prompt is shorter, it will be padded to this length.
|
| 987 |
+
|
| 988 |
+
Examples:
|
| 989 |
+
|
| 990 |
+
Returns:
|
| 991 |
+
[`~HeliosPipelineOutput`] or `tuple`:
|
| 992 |
+
If `return_dict` is `True`, [`HeliosPipelineOutput`] is returned, otherwise a `tuple` is returned where
|
| 993 |
+
the first element is a list with the generated images and the second element is a list of `bool`s
|
| 994 |
+
indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
|
| 995 |
+
"""
|
| 996 |
+
|
| 997 |
+
if image is not None and video is not None:
|
| 998 |
+
raise ValueError("image and video cannot be provided simultaneously")
|
| 999 |
+
|
| 1000 |
+
if use_kv_cache:
|
| 1001 |
+
self.transformer.enable_kv_cache()
|
| 1002 |
+
|
| 1003 |
+
if use_interpolate_prompt:
|
| 1004 |
+
assert num_videos_per_prompt == 1, f"num_videos_per_prompt must be 1, got {num_videos_per_prompt}"
|
| 1005 |
+
assert isinstance(prompt, list), "prompt must be a list"
|
| 1006 |
+
assert len(prompt) == len(interpolate_time_list), (
|
| 1007 |
+
f"Length mismatch: {len(prompt)} vs {len(interpolate_time_list)}"
|
| 1008 |
+
)
|
| 1009 |
+
assert min(interpolate_time_list) > interpolation_steps, (
|
| 1010 |
+
f"Minimum value {min(interpolate_time_list)} must be greater than {interpolation_steps}"
|
| 1011 |
+
)
|
| 1012 |
+
interpolate_interval_idx = None
|
| 1013 |
+
interpolate_embeds = None
|
| 1014 |
+
interpolate_cumulative_list = list(accumulate(interpolate_time_list))
|
| 1015 |
+
|
| 1016 |
+
anti_drifting_helper = None
|
| 1017 |
+
if use_adaptive_anti_drifting:
|
| 1018 |
+
anti_drifting_helper = AdaptiveAntiDrifting(
|
| 1019 |
+
rho_mu=anti_drift_rho_mu,
|
| 1020 |
+
rho_sigma=anti_drift_rho_sigma,
|
| 1021 |
+
delta_mu=anti_drift_delta_mu,
|
| 1022 |
+
delta_sigma=anti_drift_delta_sigma,
|
| 1023 |
+
device=self._execution_device,
|
| 1024 |
+
dtype=torch.float32,
|
| 1025 |
+
)
|
| 1026 |
+
|
| 1027 |
+
history_sizes = sorted(history_sizes, reverse=True) # From big to small
|
| 1028 |
+
|
| 1029 |
+
latents_mean = (
|
| 1030 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 1031 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 1032 |
+
.to(self.vae.device, self.vae.dtype)
|
| 1033 |
+
)
|
| 1034 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
| 1035 |
+
self.vae.device, self.vae.dtype
|
| 1036 |
+
)
|
| 1037 |
+
|
| 1038 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
| 1039 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
| 1040 |
+
|
| 1041 |
+
# 1. Check inputs. Raise error if not correct
|
| 1042 |
+
self.check_inputs(
|
| 1043 |
+
prompt,
|
| 1044 |
+
negative_prompt,
|
| 1045 |
+
height,
|
| 1046 |
+
width,
|
| 1047 |
+
prompt_embeds,
|
| 1048 |
+
negative_prompt_embeds,
|
| 1049 |
+
callback_on_step_end_tensor_inputs,
|
| 1050 |
+
)
|
| 1051 |
+
|
| 1052 |
+
num_frames = max(num_frames, 1)
|
| 1053 |
+
|
| 1054 |
+
self._guidance_scale = guidance_scale
|
| 1055 |
+
self._attention_kwargs = attention_kwargs
|
| 1056 |
+
self._current_timestep = None
|
| 1057 |
+
self._interrupt = False
|
| 1058 |
+
|
| 1059 |
+
device = self._execution_device
|
| 1060 |
+
vae_dtype = self.vae.dtype
|
| 1061 |
+
|
| 1062 |
+
# 2. Define call parameters
|
| 1063 |
+
if use_interpolate_prompt or (prompt is not None and isinstance(prompt, str)):
|
| 1064 |
+
batch_size = 1
|
| 1065 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 1066 |
+
batch_size = len(prompt)
|
| 1067 |
+
else:
|
| 1068 |
+
batch_size = prompt_embeds.shape[0]
|
| 1069 |
+
|
| 1070 |
+
# 3. Encode input prompt
|
| 1071 |
+
all_prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask = (
|
| 1072 |
+
self.encode_prompt(
|
| 1073 |
+
prompt=prompt,
|
| 1074 |
+
negative_prompt=negative_prompt,
|
| 1075 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 1076 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 1077 |
+
prompt_embeds=prompt_embeds,
|
| 1078 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1079 |
+
max_sequence_length=max_sequence_length,
|
| 1080 |
+
device=device,
|
| 1081 |
+
)
|
| 1082 |
+
)
|
| 1083 |
+
|
| 1084 |
+
transformer_dtype = self.transformer.dtype
|
| 1085 |
+
all_prompt_embeds = all_prompt_embeds.to(transformer_dtype)
|
| 1086 |
+
if negative_prompt_embeds is not None:
|
| 1087 |
+
if use_interpolate_prompt:
|
| 1088 |
+
negative_prompt_embeds = negative_prompt_embeds[0].unsqueeze(0)
|
| 1089 |
+
negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
| 1090 |
+
|
| 1091 |
+
# 4. Prepare image
|
| 1092 |
+
if image is not None:
|
| 1093 |
+
image = self.video_processor.preprocess(image, height=height, width=width)
|
| 1094 |
+
image_latents, fake_image_latents = self.prepare_image_latents(
|
| 1095 |
+
image,
|
| 1096 |
+
latents_mean=latents_mean,
|
| 1097 |
+
latents_std=latents_std,
|
| 1098 |
+
dtype=torch.float32,
|
| 1099 |
+
device=device,
|
| 1100 |
+
generator=generator,
|
| 1101 |
+
latents=image_latents,
|
| 1102 |
+
fake_latents=fake_image_latents,
|
| 1103 |
+
)
|
| 1104 |
+
|
| 1105 |
+
if image_latents is not None and add_noise_to_image_latents:
|
| 1106 |
+
image_noise_sigma = (
|
| 1107 |
+
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
|
| 1108 |
+
+ image_noise_sigma_min
|
| 1109 |
+
)
|
| 1110 |
+
image_latents = (
|
| 1111 |
+
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1112 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1113 |
+
)
|
| 1114 |
+
fake_image_noise_sigma = (
|
| 1115 |
+
torch.rand(1, device=device, generator=generator) * (video_noise_sigma_max - video_noise_sigma_min)
|
| 1116 |
+
+ video_noise_sigma_min
|
| 1117 |
+
)
|
| 1118 |
+
fake_image_latents = (
|
| 1119 |
+
fake_image_noise_sigma * randn_tensor(fake_image_latents.shape, generator=generator, device=device)
|
| 1120 |
+
+ (1 - fake_image_noise_sigma) * fake_image_latents
|
| 1121 |
+
)
|
| 1122 |
+
|
| 1123 |
+
if video is not None:
|
| 1124 |
+
video = self.video_processor.preprocess_video(video, height=height, width=width)
|
| 1125 |
+
image_latents, video_latents = self.prepare_video_latents(
|
| 1126 |
+
video,
|
| 1127 |
+
latents_mean=latents_mean,
|
| 1128 |
+
latents_std=latents_std,
|
| 1129 |
+
latent_window_size=latent_window_size,
|
| 1130 |
+
dtype=torch.float32,
|
| 1131 |
+
device=device,
|
| 1132 |
+
generator=generator,
|
| 1133 |
+
latents=video_latents,
|
| 1134 |
+
)
|
| 1135 |
+
|
| 1136 |
+
if video_latents is not None and add_noise_to_video_latents:
|
| 1137 |
+
image_noise_sigma = (
|
| 1138 |
+
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
|
| 1139 |
+
+ image_noise_sigma_min
|
| 1140 |
+
)
|
| 1141 |
+
image_latents = (
|
| 1142 |
+
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1143 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1144 |
+
)
|
| 1145 |
+
|
| 1146 |
+
noisy_latents_chunks = []
|
| 1147 |
+
num_latent_chunks = video_latents.shape[2] // latent_window_size
|
| 1148 |
+
for i in range(num_latent_chunks):
|
| 1149 |
+
chunk_start = i * latent_window_size
|
| 1150 |
+
chunk_end = chunk_start + latent_window_size
|
| 1151 |
+
latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :]
|
| 1152 |
+
|
| 1153 |
+
chunk_frames = latent_chunk.shape[2]
|
| 1154 |
+
frame_sigmas = (
|
| 1155 |
+
torch.rand(chunk_frames, device=device, generator=generator)
|
| 1156 |
+
* (video_noise_sigma_max - video_noise_sigma_min)
|
| 1157 |
+
+ video_noise_sigma_min
|
| 1158 |
+
)
|
| 1159 |
+
frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1)
|
| 1160 |
+
|
| 1161 |
+
noisy_chunk = (
|
| 1162 |
+
frame_sigmas * randn_tensor(latent_chunk.shape, generator=generator, device=device)
|
| 1163 |
+
+ (1 - frame_sigmas) * latent_chunk
|
| 1164 |
+
)
|
| 1165 |
+
noisy_latents_chunks.append(noisy_chunk)
|
| 1166 |
+
video_latents = torch.cat(noisy_latents_chunks, dim=2)
|
| 1167 |
+
|
| 1168 |
+
# 5. Prepare latent variables
|
| 1169 |
+
num_channels_latents = self.transformer.config.in_channels
|
| 1170 |
+
window_num_frames = (latent_window_size - 1) * self.vae_scale_factor_temporal + 1
|
| 1171 |
+
num_latent_sections = max(1, (num_frames + window_num_frames - 1) // window_num_frames)
|
| 1172 |
+
history_video = None
|
| 1173 |
+
total_generated_latent_frames = 0
|
| 1174 |
+
|
| 1175 |
+
if not is_keep_x0:
|
| 1176 |
+
history_sizes[-1] = history_sizes[-1] + 1
|
| 1177 |
+
history_latents = torch.zeros(
|
| 1178 |
+
batch_size,
|
| 1179 |
+
num_channels_latents,
|
| 1180 |
+
sum(history_sizes),
|
| 1181 |
+
height // self.vae_scale_factor_spatial,
|
| 1182 |
+
width // self.vae_scale_factor_spatial,
|
| 1183 |
+
device=device,
|
| 1184 |
+
dtype=torch.float32,
|
| 1185 |
+
)
|
| 1186 |
+
if fake_image_latents is not None:
|
| 1187 |
+
history_latents = torch.cat([history_latents, fake_image_latents], dim=2)
|
| 1188 |
+
total_generated_latent_frames += 1
|
| 1189 |
+
if video_latents is not None:
|
| 1190 |
+
history_frames = history_latents.shape[2]
|
| 1191 |
+
video_frames = video_latents.shape[2]
|
| 1192 |
+
if video_frames < history_frames:
|
| 1193 |
+
keep_frames = history_frames - video_frames
|
| 1194 |
+
history_latents = torch.cat([history_latents[:, :, :keep_frames, :, :], video_latents], dim=2)
|
| 1195 |
+
else:
|
| 1196 |
+
history_latents = video_latents
|
| 1197 |
+
total_generated_latent_frames += video_latents.shape[2]
|
| 1198 |
+
|
| 1199 |
+
# 6. Denoising loop
|
| 1200 |
+
if use_interpolate_prompt:
|
| 1201 |
+
if num_latent_sections < max(interpolate_cumulative_list):
|
| 1202 |
+
num_latent_sections = sum(interpolate_cumulative_list)
|
| 1203 |
+
print(f"Update num_latent_sections to: {num_latent_sections}")
|
| 1204 |
+
|
| 1205 |
+
for k in range(num_latent_sections):
|
| 1206 |
+
if use_interpolate_prompt:
|
| 1207 |
+
assert num_latent_sections >= max(interpolate_cumulative_list)
|
| 1208 |
+
|
| 1209 |
+
current_interval_idx = 0
|
| 1210 |
+
for idx, cumulative_val in enumerate(interpolate_cumulative_list):
|
| 1211 |
+
if k < cumulative_val:
|
| 1212 |
+
current_interval_idx = idx
|
| 1213 |
+
break
|
| 1214 |
+
|
| 1215 |
+
if current_interval_idx == 0:
|
| 1216 |
+
prompt_embeds = all_prompt_embeds[0].unsqueeze(0)
|
| 1217 |
+
else:
|
| 1218 |
+
interval_start = interpolate_cumulative_list[current_interval_idx - 1]
|
| 1219 |
+
position_in_interval = k - interval_start
|
| 1220 |
+
|
| 1221 |
+
if position_in_interval < interpolation_steps:
|
| 1222 |
+
if interpolate_embeds is None or interpolate_interval_idx != current_interval_idx:
|
| 1223 |
+
interpolate_embeds = self.interpolate_prompt_embeds(
|
| 1224 |
+
prompt_embeds_1=all_prompt_embeds[current_interval_idx - 1].unsqueeze(0),
|
| 1225 |
+
prompt_embeds_2=all_prompt_embeds[current_interval_idx].unsqueeze(0),
|
| 1226 |
+
interpolation_steps=interpolation_steps,
|
| 1227 |
+
)
|
| 1228 |
+
interpolate_interval_idx = current_interval_idx
|
| 1229 |
+
|
| 1230 |
+
prompt_embeds = interpolate_embeds[position_in_interval]
|
| 1231 |
+
else:
|
| 1232 |
+
prompt_embeds = all_prompt_embeds[current_interval_idx].unsqueeze(0)
|
| 1233 |
+
else:
|
| 1234 |
+
prompt_embeds = all_prompt_embeds
|
| 1235 |
+
|
| 1236 |
+
is_first_section = k == 0
|
| 1237 |
+
is_second_section = k == 1
|
| 1238 |
+
if is_keep_x0:
|
| 1239 |
+
if is_first_section:
|
| 1240 |
+
history_sizes_first_section = [1] + history_sizes.copy()
|
| 1241 |
+
history_latents_first_section = torch.zeros(
|
| 1242 |
+
batch_size,
|
| 1243 |
+
num_channels_latents,
|
| 1244 |
+
sum(history_sizes_first_section),
|
| 1245 |
+
height // self.vae_scale_factor_spatial,
|
| 1246 |
+
width // self.vae_scale_factor_spatial,
|
| 1247 |
+
device=device,
|
| 1248 |
+
dtype=torch.float32,
|
| 1249 |
+
)
|
| 1250 |
+
if fake_image_latents is not None:
|
| 1251 |
+
history_latents_first_section = torch.cat(
|
| 1252 |
+
[history_latents_first_section, fake_image_latents], dim=2
|
| 1253 |
+
)
|
| 1254 |
+
if video_latents is not None:
|
| 1255 |
+
history_frames = history_latents_first_section.shape[2]
|
| 1256 |
+
video_frames = video_latents.shape[2]
|
| 1257 |
+
if video_frames < history_frames:
|
| 1258 |
+
keep_frames = history_frames - video_frames
|
| 1259 |
+
history_latents_first_section = torch.cat(
|
| 1260 |
+
[history_latents_first_section[:, :, :keep_frames, :, :], video_latents], dim=2
|
| 1261 |
+
)
|
| 1262 |
+
else:
|
| 1263 |
+
history_latents_first_section = video_latents
|
| 1264 |
+
|
| 1265 |
+
indices = torch.arange(0, sum([1, *history_sizes, latent_window_size]))
|
| 1266 |
+
(
|
| 1267 |
+
indices_prefix,
|
| 1268 |
+
indices_latents_history_long,
|
| 1269 |
+
indices_latents_history_mid,
|
| 1270 |
+
indices_latents_history_1x,
|
| 1271 |
+
indices_hidden_states,
|
| 1272 |
+
) = indices.split([1, *history_sizes, latent_window_size], dim=0)
|
| 1273 |
+
indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0)
|
| 1274 |
+
|
| 1275 |
+
latents_prefix, latents_history_long, latents_history_mid, latents_history_1x = (
|
| 1276 |
+
history_latents_first_section[:, :, -sum(history_sizes_first_section) :].split(
|
| 1277 |
+
history_sizes_first_section, dim=2
|
| 1278 |
+
)
|
| 1279 |
+
)
|
| 1280 |
+
if image_latents is not None:
|
| 1281 |
+
latents_prefix = image_latents
|
| 1282 |
+
latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2)
|
| 1283 |
+
else:
|
| 1284 |
+
indices = torch.arange(0, sum([1, *history_sizes, latent_window_size]))
|
| 1285 |
+
(
|
| 1286 |
+
indices_prefix,
|
| 1287 |
+
indices_latents_history_long,
|
| 1288 |
+
indices_latents_history_mid,
|
| 1289 |
+
indices_latents_history_1x,
|
| 1290 |
+
indices_hidden_states,
|
| 1291 |
+
) = indices.split([1, *history_sizes, latent_window_size], dim=0)
|
| 1292 |
+
indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0)
|
| 1293 |
+
|
| 1294 |
+
latents_prefix = image_latents
|
| 1295 |
+
latents_history_long, latents_history_mid, latents_history_1x = history_latents[
|
| 1296 |
+
:, :, -sum(history_sizes) :
|
| 1297 |
+
].split(history_sizes, dim=2)
|
| 1298 |
+
latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2)
|
| 1299 |
+
else:
|
| 1300 |
+
indices = torch.arange(0, sum([*history_sizes, latent_window_size]))
|
| 1301 |
+
(
|
| 1302 |
+
indices_latents_history_long,
|
| 1303 |
+
indices_latents_history_mid,
|
| 1304 |
+
indices_latents_history_short,
|
| 1305 |
+
indices_hidden_states,
|
| 1306 |
+
) = indices.split([*history_sizes, latent_window_size], dim=0)
|
| 1307 |
+
latents_history_long, latents_history_mid, latents_history_short = history_latents[
|
| 1308 |
+
:, :, -sum(history_sizes) :
|
| 1309 |
+
].split(history_sizes, dim=2)
|
| 1310 |
+
|
| 1311 |
+
latents = self.prepare_latents(
|
| 1312 |
+
batch_size,
|
| 1313 |
+
num_channels_latents,
|
| 1314 |
+
height,
|
| 1315 |
+
width,
|
| 1316 |
+
window_num_frames,
|
| 1317 |
+
dtype=torch.float32,
|
| 1318 |
+
device=device,
|
| 1319 |
+
generator=generator,
|
| 1320 |
+
latents=None,
|
| 1321 |
+
)
|
| 1322 |
+
|
| 1323 |
+
if not is_enable_stage2:
|
| 1324 |
+
self.scheduler.set_timesteps(num_inference_steps, mu=1, device=device)
|
| 1325 |
+
|
| 1326 |
+
if use_dynamic_shifting:
|
| 1327 |
+
sigmas = torch.linspace(
|
| 1328 |
+
0.999, 0.0, steps=num_inference_steps + 1, dtype=torch.float32, device=device
|
| 1329 |
+
)[:-1]
|
| 1330 |
+
sigmas = apply_schedule_shift(
|
| 1331 |
+
sigmas=sigmas,
|
| 1332 |
+
noise=latents,
|
| 1333 |
+
base_seq_len=self.scheduler.config.get("base_image_seq_len", 256),
|
| 1334 |
+
max_seq_len=self.scheduler.config.get("max_image_seq_len", 4096),
|
| 1335 |
+
base_shift=self.scheduler.config.get("base_shift", 0.5),
|
| 1336 |
+
max_shift=self.scheduler.config.get("max_shift", 1.15),
|
| 1337 |
+
time_shift_type=time_shift_type,
|
| 1338 |
+
)
|
| 1339 |
+
timesteps = sigmas * 1000.0 # rescale to [0, 1000.0)
|
| 1340 |
+
timesteps = timesteps.to(device)
|
| 1341 |
+
sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
|
| 1342 |
+
self.scheduler.timesteps = timesteps
|
| 1343 |
+
self.scheduler.sigmas = sigmas
|
| 1344 |
+
|
| 1345 |
+
timesteps = self.scheduler.timesteps
|
| 1346 |
+
|
| 1347 |
+
dmd_sigmas = None
|
| 1348 |
+
dmd_timesteps = None
|
| 1349 |
+
if use_dmd:
|
| 1350 |
+
dmd_sigmas = self.scheduler.sigmas.to(self.transformer.device)
|
| 1351 |
+
dmd_timesteps = self.scheduler.timesteps.to(self.transformer.device)
|
| 1352 |
+
|
| 1353 |
+
self._num_timesteps = len(timesteps)
|
| 1354 |
+
else:
|
| 1355 |
+
num_inference_steps = (
|
| 1356 |
+
sum(stage2_num_inference_steps_list) * 2
|
| 1357 |
+
if is_amplify_first_chunk and use_dmd and is_first_section
|
| 1358 |
+
else sum(stage2_num_inference_steps_list)
|
| 1359 |
+
)
|
| 1360 |
+
|
| 1361 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 1362 |
+
if is_enable_stage2:
|
| 1363 |
+
latents = self.stage2_sample(
|
| 1364 |
+
latents=latents,
|
| 1365 |
+
stage2_num_stages=stage2_num_stages,
|
| 1366 |
+
stage2_num_inference_steps_list=stage2_num_inference_steps_list,
|
| 1367 |
+
prompt_embeds=prompt_embeds,
|
| 1368 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1369 |
+
guidance_scale=guidance_scale,
|
| 1370 |
+
indices_hidden_states=indices_hidden_states,
|
| 1371 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1372 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1373 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1374 |
+
latents_history_short=latents_history_short,
|
| 1375 |
+
latents_history_mid=latents_history_mid,
|
| 1376 |
+
latents_history_long=latents_history_long,
|
| 1377 |
+
attention_kwargs=attention_kwargs,
|
| 1378 |
+
device=device,
|
| 1379 |
+
transformer_dtype=transformer_dtype,
|
| 1380 |
+
scheduler_type=scheduler_type,
|
| 1381 |
+
use_dynamic_shifting=use_dynamic_shifting,
|
| 1382 |
+
time_shift_type=time_shift_type,
|
| 1383 |
+
generator=generator,
|
| 1384 |
+
# ------------ CFG Zero ------------
|
| 1385 |
+
use_cfg_zero_star=use_cfg_zero_star,
|
| 1386 |
+
use_zero_init=use_zero_init,
|
| 1387 |
+
zero_steps=zero_steps,
|
| 1388 |
+
# -------------- DMD --------------
|
| 1389 |
+
use_dmd=use_dmd,
|
| 1390 |
+
is_amplify_first_chunk=is_amplify_first_chunk and is_first_section,
|
| 1391 |
+
# ------------ Callback ------------
|
| 1392 |
+
callback_on_step_end=callback_on_step_end,
|
| 1393 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1394 |
+
progress_bar=progress_bar,
|
| 1395 |
+
)
|
| 1396 |
+
else:
|
| 1397 |
+
latents = self.stage1_sample(
|
| 1398 |
+
latents=latents,
|
| 1399 |
+
prompt_embeds=prompt_embeds,
|
| 1400 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1401 |
+
timesteps=timesteps,
|
| 1402 |
+
guidance_scale=guidance_scale,
|
| 1403 |
+
indices_hidden_states=indices_hidden_states,
|
| 1404 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1405 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1406 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1407 |
+
latents_history_short=latents_history_short,
|
| 1408 |
+
latents_history_mid=latents_history_mid,
|
| 1409 |
+
latents_history_long=latents_history_long,
|
| 1410 |
+
attention_kwargs=attention_kwargs,
|
| 1411 |
+
device=device,
|
| 1412 |
+
transformer_dtype=transformer_dtype,
|
| 1413 |
+
generator=generator,
|
| 1414 |
+
# ------------ CFG Zero ------------
|
| 1415 |
+
use_cfg_zero_star=use_cfg_zero_star,
|
| 1416 |
+
use_zero_init=use_zero_init,
|
| 1417 |
+
zero_steps=zero_steps,
|
| 1418 |
+
# -------------- DMD --------------
|
| 1419 |
+
use_dmd=use_dmd,
|
| 1420 |
+
dmd_sigmas=dmd_sigmas,
|
| 1421 |
+
dmd_timesteps=dmd_timesteps,
|
| 1422 |
+
is_amplify_first_chunk=is_amplify_first_chunk and is_first_section,
|
| 1423 |
+
# ------------ Callback ------------
|
| 1424 |
+
callback_on_step_end=callback_on_step_end,
|
| 1425 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1426 |
+
progress_bar=progress_bar,
|
| 1427 |
+
)
|
| 1428 |
+
|
| 1429 |
+
if use_kv_cache:
|
| 1430 |
+
self.transformer.clear_kv_cache()
|
| 1431 |
+
|
| 1432 |
+
if use_adaptive_anti_drifting:
|
| 1433 |
+
current_mean, current_var = anti_drifting_helper.compute_latent_statistics(latents)
|
| 1434 |
+
anti_drifting_helper.update_global_statistics(current_mean, current_var)
|
| 1435 |
+
has_drift = anti_drifting_helper.detect_drift(current_mean, current_var)
|
| 1436 |
+
|
| 1437 |
+
if has_drift and k < num_latent_sections - 1:
|
| 1438 |
+
print(
|
| 1439 |
+
f"Drift detected at chunk {k + 1}/{num_latent_sections}. Applying Frame-Aware Corruption."
|
| 1440 |
+
)
|
| 1441 |
+
latents = anti_drifting_helper.apply_frame_aware_corruption(
|
| 1442 |
+
latents,
|
| 1443 |
+
corruption_strength=anti_drift_corruption_strength,
|
| 1444 |
+
generator=generator,
|
| 1445 |
+
)
|
| 1446 |
+
|
| 1447 |
+
if is_keep_x0 and (
|
| 1448 |
+
(is_first_section and image_latents is None) or (is_skip_first_section and is_second_section)
|
| 1449 |
+
):
|
| 1450 |
+
image_latents = latents[:, :, 0:1, :, :]
|
| 1451 |
+
|
| 1452 |
+
total_generated_latent_frames += latents.shape[2]
|
| 1453 |
+
history_latents = torch.cat([history_latents, latents], dim=2)
|
| 1454 |
+
real_history_latents = history_latents[:, :, -total_generated_latent_frames:]
|
| 1455 |
+
index_slice = (
|
| 1456 |
+
slice(None),
|
| 1457 |
+
slice(None),
|
| 1458 |
+
slice(-latent_window_size, None),
|
| 1459 |
+
)
|
| 1460 |
+
|
| 1461 |
+
if vae_decode_type == "default":
|
| 1462 |
+
current_latents = real_history_latents[index_slice].to(vae_dtype) / latents_std + latents_mean
|
| 1463 |
+
current_video = self.vae.decode(current_latents, return_dict=False)[0]
|
| 1464 |
+
|
| 1465 |
+
if history_video is None:
|
| 1466 |
+
history_video = current_video
|
| 1467 |
+
else:
|
| 1468 |
+
history_video = torch.cat([history_video, current_video], dim=2)
|
| 1469 |
+
|
| 1470 |
+
self._current_timestep = None
|
| 1471 |
+
|
| 1472 |
+
if output_type != "latent":
|
| 1473 |
+
if vae_decode_type == "default_batch":
|
| 1474 |
+
total_latent_frames = real_history_latents.shape[2]
|
| 1475 |
+
batch_size = real_history_latents.shape[0]
|
| 1476 |
+
num_chunks = total_latent_frames // latent_window_size
|
| 1477 |
+
|
| 1478 |
+
chunks = (
|
| 1479 |
+
real_history_latents.reshape(
|
| 1480 |
+
batch_size,
|
| 1481 |
+
-1,
|
| 1482 |
+
num_chunks,
|
| 1483 |
+
latent_window_size,
|
| 1484 |
+
real_history_latents.shape[-2],
|
| 1485 |
+
real_history_latents.shape[-1],
|
| 1486 |
+
)
|
| 1487 |
+
.permute(0, 2, 1, 3, 4, 5)
|
| 1488 |
+
.reshape(
|
| 1489 |
+
batch_size * num_chunks,
|
| 1490 |
+
-1,
|
| 1491 |
+
latent_window_size,
|
| 1492 |
+
real_history_latents.shape[-2],
|
| 1493 |
+
real_history_latents.shape[-1],
|
| 1494 |
+
)
|
| 1495 |
+
)
|
| 1496 |
+
|
| 1497 |
+
chunks = chunks.to(vae_dtype) / latents_std + latents_mean
|
| 1498 |
+
batch_video = self.vae.decode(chunks, return_dict=False)[0]
|
| 1499 |
+
|
| 1500 |
+
video_frames_per_chunk = batch_video.shape[2]
|
| 1501 |
+
history_video = (
|
| 1502 |
+
batch_video.reshape(
|
| 1503 |
+
batch_size,
|
| 1504 |
+
num_chunks,
|
| 1505 |
+
-1,
|
| 1506 |
+
video_frames_per_chunk,
|
| 1507 |
+
batch_video.shape[-2],
|
| 1508 |
+
batch_video.shape[-1],
|
| 1509 |
+
)
|
| 1510 |
+
.permute(0, 2, 1, 3, 4, 5)
|
| 1511 |
+
.reshape(
|
| 1512 |
+
batch_size,
|
| 1513 |
+
-1,
|
| 1514 |
+
num_chunks * video_frames_per_chunk,
|
| 1515 |
+
batch_video.shape[-2],
|
| 1516 |
+
batch_video.shape[-1],
|
| 1517 |
+
)
|
| 1518 |
+
)
|
| 1519 |
+
|
| 1520 |
+
generated_frames = history_video.size(2)
|
| 1521 |
+
generated_frames = (
|
| 1522 |
+
generated_frames - 1
|
| 1523 |
+
) // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
|
| 1524 |
+
history_video = history_video[:, :, :generated_frames]
|
| 1525 |
+
video = self.video_processor.postprocess_video(history_video, output_type=output_type)
|
| 1526 |
+
else:
|
| 1527 |
+
video = real_history_latents
|
| 1528 |
+
|
| 1529 |
+
# Offload all models
|
| 1530 |
+
self.maybe_free_model_hooks()
|
| 1531 |
+
|
| 1532 |
+
if not return_dict:
|
| 1533 |
+
return (video,)
|
| 1534 |
+
|
| 1535 |
+
return HeliosPipelineOutput(frames=video)
|
Helios/_DEV/helios/pipelines/pipeline_helios_ode.py
ADDED
|
@@ -0,0 +1,1510 @@
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import html
|
| 16 |
+
import math
|
| 17 |
+
from enum import Enum
|
| 18 |
+
from itertools import accumulate
|
| 19 |
+
from typing import Any, Callable, Dict, List, Literal, Optional, Union
|
| 20 |
+
|
| 21 |
+
import regex as re
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from einops import rearrange
|
| 25 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 26 |
+
|
| 27 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 28 |
+
from diffusers.image_processor import PipelineImageInput
|
| 29 |
+
from diffusers.loaders import WanLoraLoaderMixin
|
| 30 |
+
from diffusers.models import AutoencoderKLWan
|
| 31 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 32 |
+
from diffusers.schedulers import UniPCMultistepScheduler
|
| 33 |
+
from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
|
| 34 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 35 |
+
from diffusers.video_processor import VideoProcessor
|
| 36 |
+
|
| 37 |
+
from ..modules.transformer_helios import HeliosTransformer3DModel
|
| 38 |
+
from ..scheduler.scheduling_helios import HeliosScheduler
|
| 39 |
+
from ..utils.utils_base import AdaptiveAntiDrifting, apply_schedule_shift
|
| 40 |
+
from ..utils.utils_helios_post import add_noise, convert_flow_pred_to_x0
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if is_torch_xla_available():
|
| 44 |
+
import torch_xla.core.xla_model as xm
|
| 45 |
+
|
| 46 |
+
XLA_AVAILABLE = True
|
| 47 |
+
else:
|
| 48 |
+
XLA_AVAILABLE = False
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 51 |
+
|
| 52 |
+
if is_ftfy_available():
|
| 53 |
+
import ftfy
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
EXAMPLE_DOC_STRING = """
|
| 57 |
+
Examples:
|
| 58 |
+
```python
|
| 59 |
+
>>> import torch
|
| 60 |
+
>>> from diffusers.utils import export_to_video
|
| 61 |
+
>>> from diffusers import AutoencoderKLWan, HeliosPipeline
|
| 62 |
+
|
| 63 |
+
>>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled
|
| 64 |
+
>>> model_id = "BestWishYsh/Helios-Base"
|
| 65 |
+
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 66 |
+
>>> pipe = HeliosPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
|
| 67 |
+
>>> pipe.to("cuda")
|
| 68 |
+
|
| 69 |
+
>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
|
| 70 |
+
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
| 71 |
+
|
| 72 |
+
>>> output = pipe(
|
| 73 |
+
... prompt=prompt,
|
| 74 |
+
... negative_prompt=negative_prompt,
|
| 75 |
+
... height=384,
|
| 76 |
+
... width=640,
|
| 77 |
+
... num_frames=132,
|
| 78 |
+
... guidance_scale=5.0,
|
| 79 |
+
... ).frames[0]
|
| 80 |
+
>>> export_to_video(output, "output.mp4", fps=24)
|
| 81 |
+
```
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@torch.amp.autocast("cuda", dtype=torch.float32)
|
| 86 |
+
def optimized_scale(positive_flat, negative_flat):
|
| 87 |
+
# Calculate dot production
|
| 88 |
+
dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)
|
| 89 |
+
|
| 90 |
+
# Squared norm of uncondition
|
| 91 |
+
squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
|
| 92 |
+
|
| 93 |
+
# st_star = v_cond^T * v_uncond / ||v_uncond||^2
|
| 94 |
+
st_star = dot_product / squared_norm
|
| 95 |
+
|
| 96 |
+
return st_star
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def basic_clean(text):
|
| 100 |
+
text = ftfy.fix_text(text)
|
| 101 |
+
text = html.unescape(html.unescape(text))
|
| 102 |
+
return text.strip()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def whitespace_clean(text):
|
| 106 |
+
text = re.sub(r"\s+", " ", text)
|
| 107 |
+
text = text.strip()
|
| 108 |
+
return text
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def prompt_clean(text):
|
| 112 |
+
text = whitespace_clean(basic_clean(text))
|
| 113 |
+
return text
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class VAEDecodeType(str, Enum):
|
| 117 |
+
DEFAULT = "default"
|
| 118 |
+
DEFAULT_BATCH = "default_batch"
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class HeliosPipeline(DiffusionPipeline, WanLoraLoaderMixin):
|
| 122 |
+
r"""
|
| 123 |
+
Pipeline for text-to-video / image-to-video / video-to-video generation using Helios.
|
| 124 |
+
|
| 125 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 126 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
tokenizer ([`T5Tokenizer`]):
|
| 130 |
+
Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
|
| 131 |
+
specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 132 |
+
text_encoder ([`T5EncoderModel`]):
|
| 133 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
| 134 |
+
the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 135 |
+
transformer ([`HeliosTransformer3DModel`]):
|
| 136 |
+
Conditional Transformer to denoise the input latents.
|
| 137 |
+
scheduler ([`UniPCMultistepScheduler`]):
|
| 138 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 139 |
+
vae ([`AutoencoderKLWan`]):
|
| 140 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
| 144 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 145 |
+
_optional_components = ["transformer"]
|
| 146 |
+
|
| 147 |
+
def __init__(
|
| 148 |
+
self,
|
| 149 |
+
tokenizer: AutoTokenizer,
|
| 150 |
+
text_encoder: UMT5EncoderModel,
|
| 151 |
+
vae: AutoencoderKLWan,
|
| 152 |
+
scheduler: UniPCMultistepScheduler | HeliosScheduler,
|
| 153 |
+
transformer: HeliosTransformer3DModel,
|
| 154 |
+
):
|
| 155 |
+
super().__init__()
|
| 156 |
+
|
| 157 |
+
self.register_modules(
|
| 158 |
+
vae=vae,
|
| 159 |
+
text_encoder=text_encoder,
|
| 160 |
+
tokenizer=tokenizer,
|
| 161 |
+
transformer=transformer,
|
| 162 |
+
scheduler=scheduler,
|
| 163 |
+
)
|
| 164 |
+
self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
|
| 165 |
+
self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
|
| 166 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
| 167 |
+
|
| 168 |
+
def _get_t5_prompt_embeds(
|
| 169 |
+
self,
|
| 170 |
+
prompt: Union[str, List[str]] = None,
|
| 171 |
+
num_videos_per_prompt: int = 1,
|
| 172 |
+
max_sequence_length: int = 226,
|
| 173 |
+
device: Optional[torch.device] = None,
|
| 174 |
+
dtype: Optional[torch.dtype] = None,
|
| 175 |
+
):
|
| 176 |
+
device = device or self._execution_device
|
| 177 |
+
dtype = dtype or self.text_encoder.dtype
|
| 178 |
+
|
| 179 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 180 |
+
prompt = [prompt_clean(u) for u in prompt]
|
| 181 |
+
batch_size = len(prompt)
|
| 182 |
+
|
| 183 |
+
text_inputs = self.tokenizer(
|
| 184 |
+
prompt,
|
| 185 |
+
padding="max_length",
|
| 186 |
+
max_length=max_sequence_length,
|
| 187 |
+
truncation=True,
|
| 188 |
+
add_special_tokens=True,
|
| 189 |
+
return_attention_mask=True,
|
| 190 |
+
return_tensors="pt",
|
| 191 |
+
)
|
| 192 |
+
text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
| 193 |
+
seq_lens = mask.gt(0).sum(dim=1).long()
|
| 194 |
+
|
| 195 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
|
| 196 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 197 |
+
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
| 198 |
+
prompt_embeds = torch.stack(
|
| 199 |
+
[torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 203 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 204 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
| 205 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
| 206 |
+
|
| 207 |
+
return prompt_embeds, text_inputs.attention_mask.bool()
|
| 208 |
+
|
| 209 |
+
def encode_prompt(
|
| 210 |
+
self,
|
| 211 |
+
prompt: Union[str, List[str]],
|
| 212 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 213 |
+
do_classifier_free_guidance: bool = True,
|
| 214 |
+
num_videos_per_prompt: int = 1,
|
| 215 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 216 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 217 |
+
max_sequence_length: int = 226,
|
| 218 |
+
device: Optional[torch.device] = None,
|
| 219 |
+
dtype: Optional[torch.dtype] = None,
|
| 220 |
+
):
|
| 221 |
+
r"""
|
| 222 |
+
Encodes the prompt into text encoder hidden states.
|
| 223 |
+
|
| 224 |
+
Args:
|
| 225 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 226 |
+
prompt to be encoded
|
| 227 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 228 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 229 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 230 |
+
less than `1`).
|
| 231 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 232 |
+
Whether to use classifier free guidance or not.
|
| 233 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 234 |
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
| 235 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 236 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 237 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 238 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 239 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 240 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 241 |
+
argument.
|
| 242 |
+
device: (`torch.device`, *optional*):
|
| 243 |
+
torch device
|
| 244 |
+
dtype: (`torch.dtype`, *optional*):
|
| 245 |
+
torch dtype
|
| 246 |
+
"""
|
| 247 |
+
device = device or self._execution_device
|
| 248 |
+
|
| 249 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 250 |
+
if prompt is not None:
|
| 251 |
+
batch_size = len(prompt)
|
| 252 |
+
else:
|
| 253 |
+
batch_size = prompt_embeds.shape[0]
|
| 254 |
+
|
| 255 |
+
if prompt_embeds is None:
|
| 256 |
+
prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
|
| 257 |
+
prompt=prompt,
|
| 258 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 259 |
+
max_sequence_length=max_sequence_length,
|
| 260 |
+
device=device,
|
| 261 |
+
dtype=dtype,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
negative_prompt_attention_mask = None
|
| 265 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 266 |
+
negative_prompt = negative_prompt or ""
|
| 267 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
| 268 |
+
|
| 269 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 270 |
+
raise TypeError(
|
| 271 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 272 |
+
f" {type(prompt)}."
|
| 273 |
+
)
|
| 274 |
+
elif batch_size != len(negative_prompt):
|
| 275 |
+
raise ValueError(
|
| 276 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 277 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 278 |
+
" the batch size of `prompt`."
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
negative_prompt_embeds, negative_prompt_attention_mask = self._get_t5_prompt_embeds(
|
| 282 |
+
prompt=negative_prompt,
|
| 283 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 284 |
+
max_sequence_length=max_sequence_length,
|
| 285 |
+
device=device,
|
| 286 |
+
dtype=dtype,
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
|
| 290 |
+
|
| 291 |
+
def check_inputs(
|
| 292 |
+
self,
|
| 293 |
+
prompt,
|
| 294 |
+
negative_prompt,
|
| 295 |
+
height,
|
| 296 |
+
width,
|
| 297 |
+
prompt_embeds=None,
|
| 298 |
+
negative_prompt_embeds=None,
|
| 299 |
+
callback_on_step_end_tensor_inputs=None,
|
| 300 |
+
):
|
| 301 |
+
if height % 16 != 0 or width % 16 != 0:
|
| 302 |
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
| 303 |
+
|
| 304 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 305 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 306 |
+
):
|
| 307 |
+
raise ValueError(
|
| 308 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
if prompt is not None and prompt_embeds is not None:
|
| 312 |
+
raise ValueError(
|
| 313 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 314 |
+
" only forward one of the two."
|
| 315 |
+
)
|
| 316 |
+
elif negative_prompt is not None and negative_prompt_embeds is not None:
|
| 317 |
+
raise ValueError(
|
| 318 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
|
| 319 |
+
" only forward one of the two."
|
| 320 |
+
)
|
| 321 |
+
elif prompt is None and prompt_embeds is None:
|
| 322 |
+
raise ValueError(
|
| 323 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 324 |
+
)
|
| 325 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 326 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 327 |
+
elif negative_prompt is not None and (
|
| 328 |
+
not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
|
| 329 |
+
):
|
| 330 |
+
raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
|
| 331 |
+
|
| 332 |
+
def prepare_latents(
|
| 333 |
+
self,
|
| 334 |
+
batch_size: int,
|
| 335 |
+
num_channels_latents: int = 16,
|
| 336 |
+
height: int = 480,
|
| 337 |
+
width: int = 832,
|
| 338 |
+
num_frames: int = 81,
|
| 339 |
+
dtype: Optional[torch.dtype] = None,
|
| 340 |
+
device: Optional[torch.device] = None,
|
| 341 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 342 |
+
latents: Optional[torch.Tensor] = None,
|
| 343 |
+
) -> torch.Tensor:
|
| 344 |
+
if latents is not None:
|
| 345 |
+
return latents.to(device=device, dtype=dtype)
|
| 346 |
+
|
| 347 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
| 348 |
+
shape = (
|
| 349 |
+
batch_size,
|
| 350 |
+
num_channels_latents,
|
| 351 |
+
num_latent_frames,
|
| 352 |
+
int(height) // self.vae_scale_factor_spatial,
|
| 353 |
+
int(width) // self.vae_scale_factor_spatial,
|
| 354 |
+
)
|
| 355 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 356 |
+
raise ValueError(
|
| 357 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 358 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 362 |
+
return latents
|
| 363 |
+
|
| 364 |
+
def prepare_image_latents(
|
| 365 |
+
self,
|
| 366 |
+
image: torch.Tensor,
|
| 367 |
+
latents_mean: torch.Tensor,
|
| 368 |
+
latents_std: torch.Tensor,
|
| 369 |
+
dtype: Optional[torch.dtype] = None,
|
| 370 |
+
device: Optional[torch.device] = None,
|
| 371 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 372 |
+
latents: Optional[torch.Tensor] = None,
|
| 373 |
+
fake_latents: Optional[torch.Tensor] = None,
|
| 374 |
+
) -> torch.Tensor:
|
| 375 |
+
device = device or self._execution_device
|
| 376 |
+
if latents is None:
|
| 377 |
+
image = image.unsqueeze(2).to(device=device, dtype=self.vae.dtype)
|
| 378 |
+
latents = self.vae.encode(image).latent_dist.sample(generator=generator)
|
| 379 |
+
latents = (latents - latents_mean) * latents_std
|
| 380 |
+
if fake_latents is None:
|
| 381 |
+
fake_video = image.repeat(1, 1, 33, 1, 1).to(device=device, dtype=self.vae.dtype)
|
| 382 |
+
fake_latents_full = self.vae.encode(fake_video).latent_dist.sample(generator=generator)
|
| 383 |
+
fake_latents_full = (fake_latents_full - latents_mean) * latents_std
|
| 384 |
+
fake_latents = fake_latents_full[:, :, -1:, :, :]
|
| 385 |
+
return latents.to(device=device, dtype=dtype), fake_latents.to(device=device, dtype=dtype)
|
| 386 |
+
|
| 387 |
+
def prepare_video_latents(
|
| 388 |
+
self,
|
| 389 |
+
video: torch.Tensor,
|
| 390 |
+
latents_mean: torch.Tensor,
|
| 391 |
+
latents_std: torch.Tensor,
|
| 392 |
+
latent_window_size: int,
|
| 393 |
+
dtype: Optional[torch.dtype] = None,
|
| 394 |
+
device: Optional[torch.device] = None,
|
| 395 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 396 |
+
latents: Optional[torch.Tensor] = None,
|
| 397 |
+
) -> torch.Tensor:
|
| 398 |
+
device = device or self._execution_device
|
| 399 |
+
video = video.to(device=device, dtype=self.vae.dtype)
|
| 400 |
+
if latents is None:
|
| 401 |
+
num_frames = video.shape[2]
|
| 402 |
+
min_frames = (latent_window_size - 1) * 4 + 1
|
| 403 |
+
num_chunks = num_frames // min_frames
|
| 404 |
+
if num_chunks == 0:
|
| 405 |
+
raise ValueError(
|
| 406 |
+
f"Video must have at least {min_frames} frames "
|
| 407 |
+
f"(got {num_frames} frames). "
|
| 408 |
+
f"Required: (latent_window_size - 1) * 4 + 1 = ({latent_window_size} - 1) * 4 + 1 = {min_frames}"
|
| 409 |
+
)
|
| 410 |
+
total_valid_frames = num_chunks * min_frames
|
| 411 |
+
start_frame = num_frames - total_valid_frames
|
| 412 |
+
|
| 413 |
+
first_frame = video[:, :, 0:1, :, :]
|
| 414 |
+
first_frame_latent = self.vae.encode(first_frame).latent_dist.sample(generator=generator)
|
| 415 |
+
first_frame_latent = (first_frame_latent - latents_mean) * latents_std
|
| 416 |
+
|
| 417 |
+
latents_chunks = []
|
| 418 |
+
for i in range(num_chunks - 1, -1, -1):
|
| 419 |
+
chunk_start = start_frame + i * min_frames
|
| 420 |
+
chunk_end = chunk_start + min_frames
|
| 421 |
+
video_chunk = video[:, :, chunk_start:chunk_end, :, :]
|
| 422 |
+
chunk_latents = self.vae.encode(video_chunk).latent_dist.sample(generator=generator)
|
| 423 |
+
chunk_latents = (chunk_latents - latents_mean) * latents_std
|
| 424 |
+
latents_chunks.insert(0, chunk_latents)
|
| 425 |
+
latents = torch.cat(latents_chunks, dim=2)
|
| 426 |
+
return first_frame_latent.to(device=device, dtype=dtype), latents.to(device=device, dtype=dtype)
|
| 427 |
+
|
| 428 |
+
def interpolate_prompt_embeds(
|
| 429 |
+
self,
|
| 430 |
+
prompt_embeds_1: torch.Tensor,
|
| 431 |
+
prompt_embeds_2: torch.Tensor,
|
| 432 |
+
interpolation_steps: int = 4,
|
| 433 |
+
):
|
| 434 |
+
x = torch.lerp(
|
| 435 |
+
prompt_embeds_1,
|
| 436 |
+
prompt_embeds_2,
|
| 437 |
+
torch.linspace(0, 1, steps=interpolation_steps).unsqueeze(1).unsqueeze(2).to(prompt_embeds_1),
|
| 438 |
+
)
|
| 439 |
+
interpolated_prompt_embeds = list(x.chunk(interpolation_steps, dim=0))
|
| 440 |
+
return interpolated_prompt_embeds
|
| 441 |
+
|
| 442 |
+
def sample_block_noise(
|
| 443 |
+
self,
|
| 444 |
+
batch_size,
|
| 445 |
+
channel,
|
| 446 |
+
num_frames,
|
| 447 |
+
height,
|
| 448 |
+
width,
|
| 449 |
+
patch_size: tuple[int, ...] = (1, 2, 2),
|
| 450 |
+
device: torch.device | None = None,
|
| 451 |
+
generator: torch.Generator | None = None,
|
| 452 |
+
):
|
| 453 |
+
# NOTE: A generator must be provided to ensure correct and reproducible results.
|
| 454 |
+
# Creating a default generator here is a fallback only — without a fixed seed,
|
| 455 |
+
# the output will be non-deterministic and may produce incorrect results in CP context.
|
| 456 |
+
if generator is None:
|
| 457 |
+
generator = torch.Generator(device=device)
|
| 458 |
+
elif isinstance(generator, list):
|
| 459 |
+
generator = generator[0]
|
| 460 |
+
|
| 461 |
+
gamma = self.scheduler.config.gamma
|
| 462 |
+
_, ph, pw = patch_size
|
| 463 |
+
block_size = ph * pw
|
| 464 |
+
|
| 465 |
+
cov = (
|
| 466 |
+
torch.eye(block_size, device=device) * (1 + gamma)
|
| 467 |
+
- torch.ones(block_size, block_size, device=device) * gamma
|
| 468 |
+
)
|
| 469 |
+
cov += torch.eye(block_size, device=device) * 1e-8
|
| 470 |
+
cov = cov.float() # Upcast to fp32 for numerical stability — cholesky is unreliable in fp16/bf16.
|
| 471 |
+
|
| 472 |
+
L = torch.linalg.cholesky(cov)
|
| 473 |
+
block_number = batch_size * channel * num_frames * (height // ph) * (width // pw)
|
| 474 |
+
z = torch.randn(block_number, block_size, generator=generator, device=generator.device).to(device=device)
|
| 475 |
+
noise = z @ L.T
|
| 476 |
+
|
| 477 |
+
noise = noise.view(batch_size, channel, num_frames, height // ph, width // pw, ph, pw)
|
| 478 |
+
noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(batch_size, channel, num_frames, height, width)
|
| 479 |
+
|
| 480 |
+
return noise
|
| 481 |
+
|
| 482 |
+
def stage1_sample(
|
| 483 |
+
self,
|
| 484 |
+
latents: torch.Tensor = None,
|
| 485 |
+
prompt_embeds: torch.Tensor = None,
|
| 486 |
+
negative_prompt_embeds: torch.Tensor = None,
|
| 487 |
+
timesteps: torch.Tensor = None,
|
| 488 |
+
guidance_scale: Optional[float] = 5.0,
|
| 489 |
+
indices_hidden_states: torch.Tensor = None,
|
| 490 |
+
indices_latents_history_short: torch.Tensor = None,
|
| 491 |
+
indices_latents_history_mid: torch.Tensor = None,
|
| 492 |
+
indices_latents_history_long: torch.Tensor = None,
|
| 493 |
+
latents_history_short: torch.Tensor = None,
|
| 494 |
+
latents_history_mid: torch.Tensor = None,
|
| 495 |
+
latents_history_long: torch.Tensor = None,
|
| 496 |
+
attention_kwargs: Optional[dict] = None,
|
| 497 |
+
device: Optional[torch.device] = None,
|
| 498 |
+
transformer_dtype: torch.dtype = None,
|
| 499 |
+
generator: Optional[torch.Generator] = None,
|
| 500 |
+
# ------------ CFG Zero ------------
|
| 501 |
+
use_cfg_zero_star: Optional[bool] = False,
|
| 502 |
+
use_zero_init: Optional[bool] = True,
|
| 503 |
+
zero_steps: Optional[int] = 1,
|
| 504 |
+
# -------------- DMD --------------
|
| 505 |
+
use_dmd: bool = False,
|
| 506 |
+
dmd_sigmas: torch.Tensor = None,
|
| 507 |
+
dmd_timesteps: torch.Tensor = None,
|
| 508 |
+
# ------------ Callback ------------
|
| 509 |
+
callback_on_step_end: Optional[callable] = None,
|
| 510 |
+
callback_on_step_end_tensor_inputs: list = None,
|
| 511 |
+
progress_bar=None,
|
| 512 |
+
):
|
| 513 |
+
batch_size = latents.shape[0]
|
| 514 |
+
|
| 515 |
+
for i, t in enumerate(timesteps):
|
| 516 |
+
is_first_step = i == 0
|
| 517 |
+
|
| 518 |
+
if self.interrupt:
|
| 519 |
+
continue
|
| 520 |
+
|
| 521 |
+
self._current_timestep = t
|
| 522 |
+
timestep = t.expand(latents.shape[0])
|
| 523 |
+
|
| 524 |
+
latent_model_input = latents.to(transformer_dtype)
|
| 525 |
+
with self.transformer.cache_context("cond"):
|
| 526 |
+
noise_pred = self.transformer(
|
| 527 |
+
hidden_states=latent_model_input,
|
| 528 |
+
timestep=timestep,
|
| 529 |
+
encoder_hidden_states=prompt_embeds,
|
| 530 |
+
indices_hidden_states=indices_hidden_states,
|
| 531 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 532 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 533 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 534 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 535 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 536 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 537 |
+
is_first_denoising_step=is_first_step,
|
| 538 |
+
attention_kwargs=attention_kwargs,
|
| 539 |
+
return_dict=False,
|
| 540 |
+
)[0]
|
| 541 |
+
|
| 542 |
+
if self.do_classifier_free_guidance and not use_dmd:
|
| 543 |
+
with self.transformer.cache_context("uncond"):
|
| 544 |
+
noise_uncond = self.transformer(
|
| 545 |
+
hidden_states=latent_model_input,
|
| 546 |
+
timestep=timestep,
|
| 547 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 548 |
+
indices_hidden_states=indices_hidden_states,
|
| 549 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 550 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 551 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 552 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 553 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 554 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 555 |
+
is_first_denoising_step=is_first_step,
|
| 556 |
+
attention_kwargs=attention_kwargs,
|
| 557 |
+
return_dict=False,
|
| 558 |
+
)[0]
|
| 559 |
+
|
| 560 |
+
if use_cfg_zero_star:
|
| 561 |
+
noise_pred_text = noise_pred
|
| 562 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 563 |
+
negative_flat = noise_uncond.view(batch_size, -1)
|
| 564 |
+
|
| 565 |
+
alpha = optimized_scale(positive_flat, negative_flat)
|
| 566 |
+
alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
|
| 567 |
+
alpha = alpha.to(noise_pred_text.dtype)
|
| 568 |
+
|
| 569 |
+
if (i <= zero_steps) and use_zero_init:
|
| 570 |
+
noise_pred = noise_pred_text * 0.0
|
| 571 |
+
else:
|
| 572 |
+
noise_pred = noise_uncond * alpha + guidance_scale * (noise_pred_text - noise_uncond * alpha)
|
| 573 |
+
else:
|
| 574 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
| 575 |
+
|
| 576 |
+
if use_dmd:
|
| 577 |
+
pred_image_or_video = convert_flow_pred_to_x0(
|
| 578 |
+
flow_pred=noise_pred,
|
| 579 |
+
xt=latent_model_input,
|
| 580 |
+
timestep=t * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device),
|
| 581 |
+
sigmas=dmd_sigmas,
|
| 582 |
+
timesteps=dmd_timesteps,
|
| 583 |
+
)
|
| 584 |
+
if i < len(timesteps) - 1:
|
| 585 |
+
latents = add_noise(
|
| 586 |
+
pred_image_or_video,
|
| 587 |
+
randn_tensor(pred_image_or_video.shape, generator=generator, device=device),
|
| 588 |
+
timesteps[i + 1] * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device),
|
| 589 |
+
sigmas=dmd_sigmas,
|
| 590 |
+
timesteps=dmd_timesteps,
|
| 591 |
+
)
|
| 592 |
+
else:
|
| 593 |
+
latents = pred_image_or_video
|
| 594 |
+
else:
|
| 595 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 596 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 597 |
+
|
| 598 |
+
if callback_on_step_end is not None:
|
| 599 |
+
callback_kwargs = {}
|
| 600 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 601 |
+
callback_kwargs[k] = locals()[k]
|
| 602 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 603 |
+
|
| 604 |
+
latents = callback_outputs.pop("latents", latents)
|
| 605 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 606 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 607 |
+
|
| 608 |
+
progress_bar.update()
|
| 609 |
+
|
| 610 |
+
if XLA_AVAILABLE:
|
| 611 |
+
xm.mark_step()
|
| 612 |
+
|
| 613 |
+
return latents
|
| 614 |
+
|
| 615 |
+
def stage2_sample(
|
| 616 |
+
self,
|
| 617 |
+
is_first_section,
|
| 618 |
+
latents: torch.Tensor = None,
|
| 619 |
+
stage2_num_stages: int = None,
|
| 620 |
+
stage2_num_inference_steps_list: List[int] = None,
|
| 621 |
+
prompt_embeds: torch.Tensor = None,
|
| 622 |
+
negative_prompt_embeds: torch.Tensor = None,
|
| 623 |
+
guidance_scale: Optional[float] = 5.0,
|
| 624 |
+
indices_hidden_states: torch.Tensor = None,
|
| 625 |
+
indices_latents_history_short: torch.Tensor = None,
|
| 626 |
+
indices_latents_history_mid: torch.Tensor = None,
|
| 627 |
+
indices_latents_history_long: torch.Tensor = None,
|
| 628 |
+
latents_history_short: torch.Tensor = None,
|
| 629 |
+
latents_history_mid: torch.Tensor = None,
|
| 630 |
+
latents_history_long: torch.Tensor = None,
|
| 631 |
+
attention_kwargs: Optional[dict] = None,
|
| 632 |
+
device: Optional[torch.device] = None,
|
| 633 |
+
transformer_dtype: torch.dtype = None,
|
| 634 |
+
scheduler_type: str = "unipc", # unipc, euler
|
| 635 |
+
use_dynamic_shifting: bool = False,
|
| 636 |
+
time_shift_type: Literal["exponential", "linear"] = "linear",
|
| 637 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 638 |
+
# ------------ CFG Zero ------------
|
| 639 |
+
use_cfg_zero_star: Optional[bool] = False,
|
| 640 |
+
use_zero_init: Optional[bool] = True,
|
| 641 |
+
zero_steps: Optional[int] = 1,
|
| 642 |
+
# -------------- DMD --------------
|
| 643 |
+
use_dmd: bool = False,
|
| 644 |
+
# ------------ Callback ------------
|
| 645 |
+
callback_on_step_end: Optional[callable] = None,
|
| 646 |
+
callback_on_step_end_tensor_inputs: list = None,
|
| 647 |
+
progress_bar=None,
|
| 648 |
+
):
|
| 649 |
+
num_frames, height, width = (
|
| 650 |
+
latents.shape[-3],
|
| 651 |
+
latents.shape[-2],
|
| 652 |
+
latents.shape[-1],
|
| 653 |
+
)
|
| 654 |
+
latents = rearrange(latents, "b c t h w -> (b t) c h w")
|
| 655 |
+
for _ in range(stage2_num_stages - 1):
|
| 656 |
+
height //= 2
|
| 657 |
+
width //= 2
|
| 658 |
+
latents = (
|
| 659 |
+
F.interpolate(
|
| 660 |
+
latents,
|
| 661 |
+
size=(height, width),
|
| 662 |
+
mode="bilinear",
|
| 663 |
+
)
|
| 664 |
+
* 2
|
| 665 |
+
)
|
| 666 |
+
latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames)
|
| 667 |
+
|
| 668 |
+
batch_size = latents.shape[0]
|
| 669 |
+
if use_dmd:
|
| 670 |
+
start_point_list = [latents]
|
| 671 |
+
|
| 672 |
+
ode_stages_tensor = []
|
| 673 |
+
|
| 674 |
+
for i_s in range(stage2_num_stages):
|
| 675 |
+
num_steps = stage2_num_inference_steps_list[i_s]
|
| 676 |
+
ode_stages_tensor.append(
|
| 677 |
+
{
|
| 678 |
+
"latents": None,
|
| 679 |
+
"timesteps": None,
|
| 680 |
+
"noise_pred": None,
|
| 681 |
+
}
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
i = 0
|
| 685 |
+
for i_s in range(stage2_num_stages):
|
| 686 |
+
if use_dmd:
|
| 687 |
+
self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s] + 1, i_s, device=device)
|
| 688 |
+
self.scheduler.timesteps = self.scheduler.timesteps[:-1]
|
| 689 |
+
self.scheduler.sigmas = torch.cat([self.scheduler.sigmas[:-2], self.scheduler.sigmas[-1:]])
|
| 690 |
+
else:
|
| 691 |
+
self.scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s, device=device)
|
| 692 |
+
|
| 693 |
+
if i_s > 0:
|
| 694 |
+
height *= 2
|
| 695 |
+
width *= 2
|
| 696 |
+
num_frames = latents.shape[2]
|
| 697 |
+
latents = rearrange(latents, "b c t h w -> (b t) c h w")
|
| 698 |
+
latents = F.interpolate(latents, size=(height, width), mode="nearest")
|
| 699 |
+
latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames)
|
| 700 |
+
# Fix the stage
|
| 701 |
+
ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal
|
| 702 |
+
gamma = self.scheduler.config.gamma
|
| 703 |
+
alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)
|
| 704 |
+
beta = alpha * (1 - ori_sigma) / math.sqrt(gamma)
|
| 705 |
+
|
| 706 |
+
batch_size, channel, num_frames, height, width = latents.shape
|
| 707 |
+
noise = self.sample_block_noise(
|
| 708 |
+
batch_size,
|
| 709 |
+
channel,
|
| 710 |
+
num_frames,
|
| 711 |
+
height,
|
| 712 |
+
width,
|
| 713 |
+
self.transformer.config.patch_size,
|
| 714 |
+
device,
|
| 715 |
+
generator,
|
| 716 |
+
)
|
| 717 |
+
noise = noise.to(device=device, dtype=transformer_dtype)
|
| 718 |
+
latents = alpha * latents + beta * noise # To fix the block artifact
|
| 719 |
+
|
| 720 |
+
if use_dmd:
|
| 721 |
+
start_point_list.append(latents)
|
| 722 |
+
|
| 723 |
+
if is_first_section:
|
| 724 |
+
if i_s == 0:
|
| 725 |
+
target_timesteps = [999.0000, 935.1279, 871.2559, 807.3838]
|
| 726 |
+
elif i_s == 1:
|
| 727 |
+
target_timesteps = [743.2560, 653.9349, 564.6138, 475.2927]
|
| 728 |
+
elif i_s == 2:
|
| 729 |
+
target_timesteps = [385.6140, 289.5564, 193.4988, 97.4412]
|
| 730 |
+
else:
|
| 731 |
+
if i_s == 0:
|
| 732 |
+
target_timesteps = [999.0000, 871.2559]
|
| 733 |
+
elif i_s == 1:
|
| 734 |
+
target_timesteps = [743.2560, 564.6138]
|
| 735 |
+
elif i_s == 2:
|
| 736 |
+
target_timesteps = [385.6140, 193.4988]
|
| 737 |
+
|
| 738 |
+
current_timesteps = self.scheduler.timesteps
|
| 739 |
+
target_tensor = torch.tensor(target_timesteps, device=device, dtype=current_timesteps.dtype)
|
| 740 |
+
|
| 741 |
+
mask = torch.all(torch.abs(current_timesteps.unsqueeze(0) - target_tensor.unsqueeze(1)) >= 1e-4, dim=1)
|
| 742 |
+
new_timesteps = target_tensor[mask]
|
| 743 |
+
if len(new_timesteps) > 0:
|
| 744 |
+
timestep_id = torch.argmin(
|
| 745 |
+
(
|
| 746 |
+
new_timesteps.unsqueeze(1)
|
| 747 |
+
- self.scheduler.timesteps_per_stage[i_s].unsqueeze(0).to(new_timesteps.device)
|
| 748 |
+
).abs(),
|
| 749 |
+
dim=1,
|
| 750 |
+
)
|
| 751 |
+
new_sigmas = self.scheduler.sigmas_per_stage[i_s].to(new_timesteps.device)[timestep_id]
|
| 752 |
+
|
| 753 |
+
merged_timesteps = torch.cat([current_timesteps, new_timesteps])
|
| 754 |
+
merged_sigmas = torch.cat([self.scheduler.sigmas[:-1], new_sigmas])
|
| 755 |
+
|
| 756 |
+
sorted_indices = torch.argsort(merged_timesteps, descending=True)
|
| 757 |
+
self.scheduler.timesteps = merged_timesteps[sorted_indices]
|
| 758 |
+
self.scheduler.sigmas = torch.cat([merged_sigmas[sorted_indices], self.scheduler.sigmas[-1:]])
|
| 759 |
+
|
| 760 |
+
if use_dynamic_shifting:
|
| 761 |
+
temp_sigmas = apply_schedule_shift(
|
| 762 |
+
self.scheduler.sigmas,
|
| 763 |
+
latents,
|
| 764 |
+
base_seq_len=self.scheduler.config.get("base_image_seq_len", 256),
|
| 765 |
+
max_seq_len=self.scheduler.config.get("max_image_seq_len", 4096),
|
| 766 |
+
base_shift=self.scheduler.config.get("base_shift", 0.5),
|
| 767 |
+
max_shift=self.scheduler.config.get("max_shift", 1.15),
|
| 768 |
+
time_shift_type=time_shift_type,
|
| 769 |
+
)
|
| 770 |
+
temp_timesteps = self.scheduler.timesteps_per_stage[i_s].min() + temp_sigmas[:-1] * (
|
| 771 |
+
self.scheduler.timesteps_per_stage[i_s].max() - self.scheduler.timesteps_per_stage[i_s].min()
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
self.scheduler.sigmas = temp_sigmas
|
| 775 |
+
self.scheduler.timesteps = temp_timesteps
|
| 776 |
+
|
| 777 |
+
timesteps = self.scheduler.timesteps
|
| 778 |
+
|
| 779 |
+
num_steps = len(timesteps)
|
| 780 |
+
ode_stages_tensor[i_s]["timesteps"] = torch.zeros(num_steps, dtype=torch.float32, device="cpu")
|
| 781 |
+
|
| 782 |
+
for idx, t in enumerate(timesteps):
|
| 783 |
+
if idx == 0:
|
| 784 |
+
batch_size, c, t_dim, h, w = latents.shape
|
| 785 |
+
num_steps = len(timesteps)
|
| 786 |
+
|
| 787 |
+
ode_stages_tensor[i_s]["latents"] = torch.zeros(
|
| 788 |
+
num_steps + 1, batch_size, c, t_dim, h, w, dtype=torch.float32, device="cpu"
|
| 789 |
+
)
|
| 790 |
+
ode_stages_tensor[i_s]["noise_pred"] = torch.zeros(
|
| 791 |
+
num_steps, batch_size, c, t_dim, h, w, dtype=torch.float32, device="cpu"
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
is_first_step = i_s == 0 and idx == 0
|
| 795 |
+
|
| 796 |
+
timestep = t.expand(latents.shape[0]).to(torch.int64)
|
| 797 |
+
|
| 798 |
+
ode_stages_tensor[i_s]["latents"][idx] = latents.detach().cpu()
|
| 799 |
+
ode_stages_tensor[i_s]["timesteps"][idx] = t.item()
|
| 800 |
+
|
| 801 |
+
with self.transformer.cache_context("cond"):
|
| 802 |
+
noise_pred = self.transformer(
|
| 803 |
+
hidden_states=latents.to(transformer_dtype),
|
| 804 |
+
timestep=timestep,
|
| 805 |
+
encoder_hidden_states=prompt_embeds,
|
| 806 |
+
attention_kwargs=attention_kwargs,
|
| 807 |
+
return_dict=False,
|
| 808 |
+
indices_hidden_states=indices_hidden_states,
|
| 809 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 810 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 811 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 812 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 813 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 814 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 815 |
+
is_first_denoising_step=is_first_step,
|
| 816 |
+
)[0]
|
| 817 |
+
|
| 818 |
+
if self.do_classifier_free_guidance:
|
| 819 |
+
with self.transformer.cache_context("cond_uncond"):
|
| 820 |
+
noise_uncond = self.transformer(
|
| 821 |
+
hidden_states=latents.to(transformer_dtype),
|
| 822 |
+
timestep=timestep,
|
| 823 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 824 |
+
attention_kwargs=attention_kwargs,
|
| 825 |
+
return_dict=False,
|
| 826 |
+
indices_hidden_states=indices_hidden_states,
|
| 827 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 828 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 829 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 830 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 831 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 832 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 833 |
+
is_first_denoising_step=is_first_step,
|
| 834 |
+
)[0]
|
| 835 |
+
|
| 836 |
+
if use_cfg_zero_star:
|
| 837 |
+
noise_pred_text = noise_pred
|
| 838 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 839 |
+
negative_flat = noise_uncond.view(batch_size, -1)
|
| 840 |
+
|
| 841 |
+
alpha = optimized_scale(positive_flat, negative_flat)
|
| 842 |
+
alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
|
| 843 |
+
alpha = alpha.to(noise_pred_text.dtype)
|
| 844 |
+
|
| 845 |
+
if (i_s == 0 and idx <= zero_steps) and use_zero_init:
|
| 846 |
+
noise_pred = noise_pred_text * 0.0
|
| 847 |
+
else:
|
| 848 |
+
noise_pred = noise_uncond * alpha + guidance_scale * (
|
| 849 |
+
noise_pred_text - noise_uncond * alpha
|
| 850 |
+
)
|
| 851 |
+
else:
|
| 852 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
| 853 |
+
|
| 854 |
+
if use_dmd:
|
| 855 |
+
pred_image_or_video = convert_flow_pred_to_x0(
|
| 856 |
+
flow_pred=noise_pred,
|
| 857 |
+
xt=latents,
|
| 858 |
+
timestep=timestep,
|
| 859 |
+
sigmas=self.scheduler.sigmas,
|
| 860 |
+
timesteps=self.scheduler.timesteps,
|
| 861 |
+
)
|
| 862 |
+
if idx < len(timesteps) - 1:
|
| 863 |
+
latents = add_noise(
|
| 864 |
+
pred_image_or_video,
|
| 865 |
+
start_point_list[i_s],
|
| 866 |
+
timesteps[idx + 1] * torch.ones(batch_size, dtype=torch.long, device=noise_pred.device),
|
| 867 |
+
sigmas=self.scheduler.sigmas,
|
| 868 |
+
timesteps=self.scheduler.timesteps,
|
| 869 |
+
)
|
| 870 |
+
else:
|
| 871 |
+
latents = pred_image_or_video
|
| 872 |
+
else:
|
| 873 |
+
if scheduler_type == "unipc":
|
| 874 |
+
latents = self.scheduler.step_unipc(noise_pred.float(), t, latents, return_dict=False)[0]
|
| 875 |
+
else:
|
| 876 |
+
latents = self.scheduler.step(noise_pred.float(), t, latents, return_dict=False)[0]
|
| 877 |
+
|
| 878 |
+
ode_stages_tensor[i_s]["noise_pred"][idx] = noise_pred.detach().cpu()
|
| 879 |
+
|
| 880 |
+
if callback_on_step_end is not None:
|
| 881 |
+
callback_kwargs = {}
|
| 882 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 883 |
+
callback_kwargs[k] = locals()[k]
|
| 884 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 885 |
+
|
| 886 |
+
latents = callback_outputs.pop("latents", latents)
|
| 887 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 888 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 889 |
+
|
| 890 |
+
progress_bar.update()
|
| 891 |
+
|
| 892 |
+
if XLA_AVAILABLE:
|
| 893 |
+
xm.mark_step()
|
| 894 |
+
|
| 895 |
+
i += 1
|
| 896 |
+
|
| 897 |
+
ode_stages_tensor[i_s]["latents"][num_steps] = latents.detach().cpu()
|
| 898 |
+
|
| 899 |
+
return latents, ode_stages_tensor
|
| 900 |
+
|
| 901 |
+
@property
|
| 902 |
+
def guidance_scale(self):
|
| 903 |
+
return self._guidance_scale
|
| 904 |
+
|
| 905 |
+
@property
|
| 906 |
+
def do_classifier_free_guidance(self):
|
| 907 |
+
return self._guidance_scale > 1.0
|
| 908 |
+
|
| 909 |
+
@property
|
| 910 |
+
def num_timesteps(self):
|
| 911 |
+
return self._num_timesteps
|
| 912 |
+
|
| 913 |
+
@property
|
| 914 |
+
def current_timestep(self):
|
| 915 |
+
return self._current_timestep
|
| 916 |
+
|
| 917 |
+
@property
|
| 918 |
+
def interrupt(self):
|
| 919 |
+
return self._interrupt
|
| 920 |
+
|
| 921 |
+
@property
|
| 922 |
+
def attention_kwargs(self):
|
| 923 |
+
return self._attention_kwargs
|
| 924 |
+
|
| 925 |
+
@torch.no_grad()
|
| 926 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 927 |
+
def __call__(
|
| 928 |
+
self,
|
| 929 |
+
prompt: Union[str, List[str]] = None,
|
| 930 |
+
negative_prompt: Union[str, List[str]] = None,
|
| 931 |
+
height: int = 384,
|
| 932 |
+
width: int = 640,
|
| 933 |
+
num_frames: int = 73,
|
| 934 |
+
num_inference_steps: int = 50,
|
| 935 |
+
guidance_scale: float = 5.0,
|
| 936 |
+
num_videos_per_prompt: Optional[int] = 1,
|
| 937 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 938 |
+
latents: Optional[torch.Tensor] = None,
|
| 939 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 940 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 941 |
+
output_type: Optional[str] = "np",
|
| 942 |
+
return_dict: bool = True,
|
| 943 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 944 |
+
callback_on_step_end: Optional[
|
| 945 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
| 946 |
+
] = None,
|
| 947 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 948 |
+
max_sequence_length: int = 512,
|
| 949 |
+
# ------------ I2V ------------
|
| 950 |
+
image: Optional[PipelineImageInput] = None,
|
| 951 |
+
image_latents: Optional[torch.Tensor] = None,
|
| 952 |
+
fake_image_latents: Optional[torch.Tensor] = None,
|
| 953 |
+
add_noise_to_image_latents: bool = True,
|
| 954 |
+
image_noise_sigma_min: float = 0.111,
|
| 955 |
+
image_noise_sigma_max: float = 0.135,
|
| 956 |
+
# ------------ V2V ------------
|
| 957 |
+
video: Optional[PipelineImageInput] = None,
|
| 958 |
+
video_latents: Optional[torch.Tensor] = None,
|
| 959 |
+
add_noise_to_video_latents: bool = True,
|
| 960 |
+
video_noise_sigma_min: float = 0.111,
|
| 961 |
+
video_noise_sigma_max: float = 0.135,
|
| 962 |
+
# ------------ Interactive ------------
|
| 963 |
+
use_interpolate_prompt: bool = False,
|
| 964 |
+
interpolate_time_list: list = [7, 7, 7],
|
| 965 |
+
interpolation_steps: int = 3,
|
| 966 |
+
# ------------ Stage 1 ------------
|
| 967 |
+
history_sizes: list = [16, 2, 1],
|
| 968 |
+
latent_window_size: int = 9,
|
| 969 |
+
use_dynamic_shifting: bool = False,
|
| 970 |
+
time_shift_type: Literal["exponential", "linear"] = "linear",
|
| 971 |
+
is_keep_x0: bool = True,
|
| 972 |
+
# ------------ Stage 2 ------------
|
| 973 |
+
is_enable_stage2: bool = False,
|
| 974 |
+
stage2_num_stages: int = 3,
|
| 975 |
+
stage2_num_inference_steps_list: list = [10, 10, 10],
|
| 976 |
+
scheduler_type: str = "unipc", # unipc, euler
|
| 977 |
+
# ------------ CFG Zero ------------
|
| 978 |
+
use_cfg_zero_star: Optional[bool] = False,
|
| 979 |
+
use_zero_init: Optional[bool] = True,
|
| 980 |
+
zero_steps: Optional[int] = 1,
|
| 981 |
+
# ------------ DMD ------------
|
| 982 |
+
use_dmd: bool = False,
|
| 983 |
+
is_skip_first_section: bool = False,
|
| 984 |
+
# ------------ Adaptive Anti-Drifting ------------
|
| 985 |
+
use_adaptive_anti_drifting: bool = False,
|
| 986 |
+
anti_drift_rho_mu: float = 0.9,
|
| 987 |
+
anti_drift_rho_sigma: float = 0.9,
|
| 988 |
+
anti_drift_delta_mu: float = 0.15,
|
| 989 |
+
anti_drift_delta_sigma: float = 0.15,
|
| 990 |
+
anti_drift_corruption_strength: float = 0.1,
|
| 991 |
+
# ------------ other ------------
|
| 992 |
+
use_kv_cache: bool = False,
|
| 993 |
+
vae_decode_type: VAEDecodeType = "default", # "default", "default_batch"
|
| 994 |
+
):
|
| 995 |
+
r"""
|
| 996 |
+
The call function to the pipeline for generation.
|
| 997 |
+
|
| 998 |
+
Args:
|
| 999 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 1000 |
+
The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
|
| 1001 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 1002 |
+
The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
|
| 1003 |
+
instead. Ignored when not using guidance (`guidance_scale` < `1`).
|
| 1004 |
+
height (`int`, defaults to `480`):
|
| 1005 |
+
The height in pixels of the generated image.
|
| 1006 |
+
width (`int`, defaults to `832`):
|
| 1007 |
+
The width in pixels of the generated image.
|
| 1008 |
+
num_frames (`int`, defaults to `81`):
|
| 1009 |
+
The number of frames in the generated video.
|
| 1010 |
+
num_inference_steps (`int`, defaults to `50`):
|
| 1011 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 1012 |
+
expense of slower inference.
|
| 1013 |
+
guidance_scale (`float`, defaults to `5.0`):
|
| 1014 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
| 1015 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
| 1016 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
| 1017 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
| 1018 |
+
the text `prompt`, usually at the expense of lower image quality.
|
| 1019 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 1020 |
+
The number of images to generate per prompt.
|
| 1021 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 1022 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 1023 |
+
generation deterministic.
|
| 1024 |
+
latents (`torch.Tensor`, *optional*):
|
| 1025 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 1026 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 1027 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 1028 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 1029 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 1030 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 1031 |
+
output_type (`str`, *optional*, defaults to `"np"`):
|
| 1032 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 1033 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 1034 |
+
Whether or not to return a [`HeliosPipelineOutput`] instead of a plain tuple.
|
| 1035 |
+
attention_kwargs (`dict`, *optional*):
|
| 1036 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 1037 |
+
`self.processor` in
|
| 1038 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 1039 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
| 1040 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
| 1041 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
| 1042 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
| 1043 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
| 1044 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 1045 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 1046 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 1047 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 1048 |
+
max_sequence_length (`int`, defaults to `512`):
|
| 1049 |
+
The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
|
| 1050 |
+
truncated. If the prompt is shorter, it will be padded to this length.
|
| 1051 |
+
|
| 1052 |
+
Examples:
|
| 1053 |
+
|
| 1054 |
+
Returns:
|
| 1055 |
+
[`~HeliosPipelineOutput`] or `tuple`:
|
| 1056 |
+
If `return_dict` is `True`, [`HeliosPipelineOutput`] is returned, otherwise a `tuple` is returned where
|
| 1057 |
+
the first element is a list with the generated images and the second element is a list of `bool`s
|
| 1058 |
+
indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
|
| 1059 |
+
"""
|
| 1060 |
+
|
| 1061 |
+
if image is not None and video is not None:
|
| 1062 |
+
raise ValueError("image and video cannot be provided simultaneously")
|
| 1063 |
+
|
| 1064 |
+
if use_kv_cache:
|
| 1065 |
+
self.transformer.enable_kv_cache()
|
| 1066 |
+
|
| 1067 |
+
if use_interpolate_prompt:
|
| 1068 |
+
assert num_videos_per_prompt == 1, f"num_videos_per_prompt must be 1, got {num_videos_per_prompt}"
|
| 1069 |
+
assert isinstance(prompt, list), "prompt must be a list"
|
| 1070 |
+
assert len(prompt) == len(interpolate_time_list), (
|
| 1071 |
+
f"Length mismatch: {len(prompt)} vs {len(interpolate_time_list)}"
|
| 1072 |
+
)
|
| 1073 |
+
assert min(interpolate_time_list) > interpolation_steps, (
|
| 1074 |
+
f"Minimum value {min(interpolate_time_list)} must be greater than {interpolation_steps}"
|
| 1075 |
+
)
|
| 1076 |
+
interpolate_interval_idx = None
|
| 1077 |
+
interpolate_embeds = None
|
| 1078 |
+
interpolate_cumulative_list = list(accumulate(interpolate_time_list))
|
| 1079 |
+
|
| 1080 |
+
anti_drifting_helper = None
|
| 1081 |
+
if use_adaptive_anti_drifting:
|
| 1082 |
+
anti_drifting_helper = AdaptiveAntiDrifting(
|
| 1083 |
+
rho_mu=anti_drift_rho_mu,
|
| 1084 |
+
rho_sigma=anti_drift_rho_sigma,
|
| 1085 |
+
delta_mu=anti_drift_delta_mu,
|
| 1086 |
+
delta_sigma=anti_drift_delta_sigma,
|
| 1087 |
+
device=self._execution_device,
|
| 1088 |
+
dtype=torch.float32,
|
| 1089 |
+
)
|
| 1090 |
+
|
| 1091 |
+
history_sizes = sorted(history_sizes, reverse=True) # From big to small
|
| 1092 |
+
|
| 1093 |
+
latents_mean = (
|
| 1094 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 1095 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 1096 |
+
.to(self.vae.device, self.vae.dtype)
|
| 1097 |
+
)
|
| 1098 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
| 1099 |
+
self.vae.device, self.vae.dtype
|
| 1100 |
+
)
|
| 1101 |
+
|
| 1102 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
| 1103 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
| 1104 |
+
|
| 1105 |
+
# 1. Check inputs. Raise error if not correct
|
| 1106 |
+
self.check_inputs(
|
| 1107 |
+
prompt,
|
| 1108 |
+
negative_prompt,
|
| 1109 |
+
height,
|
| 1110 |
+
width,
|
| 1111 |
+
prompt_embeds,
|
| 1112 |
+
negative_prompt_embeds,
|
| 1113 |
+
callback_on_step_end_tensor_inputs,
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
num_frames = max(num_frames, 1)
|
| 1117 |
+
|
| 1118 |
+
self._guidance_scale = guidance_scale
|
| 1119 |
+
self._attention_kwargs = attention_kwargs
|
| 1120 |
+
self._current_timestep = None
|
| 1121 |
+
self._interrupt = False
|
| 1122 |
+
|
| 1123 |
+
device = self._execution_device
|
| 1124 |
+
|
| 1125 |
+
# 2. Define call parameters
|
| 1126 |
+
if use_interpolate_prompt or (prompt is not None and isinstance(prompt, str)):
|
| 1127 |
+
batch_size = 1
|
| 1128 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 1129 |
+
batch_size = len(prompt)
|
| 1130 |
+
else:
|
| 1131 |
+
batch_size = prompt_embeds.shape[0]
|
| 1132 |
+
|
| 1133 |
+
# 3. Encode input prompt
|
| 1134 |
+
all_prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask = (
|
| 1135 |
+
self.encode_prompt(
|
| 1136 |
+
prompt=prompt,
|
| 1137 |
+
negative_prompt=negative_prompt,
|
| 1138 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 1139 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 1140 |
+
prompt_embeds=prompt_embeds,
|
| 1141 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1142 |
+
max_sequence_length=max_sequence_length,
|
| 1143 |
+
device=device,
|
| 1144 |
+
)
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
transformer_dtype = self.transformer.dtype
|
| 1148 |
+
all_prompt_embeds = all_prompt_embeds.to(transformer_dtype)
|
| 1149 |
+
if negative_prompt_embeds is not None:
|
| 1150 |
+
if use_interpolate_prompt:
|
| 1151 |
+
negative_prompt_embeds = negative_prompt_embeds[0].unsqueeze(0)
|
| 1152 |
+
negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
| 1153 |
+
|
| 1154 |
+
# 4. Prepare image
|
| 1155 |
+
if image is not None:
|
| 1156 |
+
image = self.video_processor.preprocess(image, height=height, width=width)
|
| 1157 |
+
image_latents, fake_image_latents = self.prepare_image_latents(
|
| 1158 |
+
image,
|
| 1159 |
+
latents_mean=latents_mean,
|
| 1160 |
+
latents_std=latents_std,
|
| 1161 |
+
dtype=torch.float32,
|
| 1162 |
+
device=device,
|
| 1163 |
+
generator=generator,
|
| 1164 |
+
latents=image_latents,
|
| 1165 |
+
fake_latents=fake_image_latents,
|
| 1166 |
+
)
|
| 1167 |
+
|
| 1168 |
+
if image_latents is not None and add_noise_to_image_latents:
|
| 1169 |
+
image_noise_sigma = (
|
| 1170 |
+
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
|
| 1171 |
+
+ image_noise_sigma_min
|
| 1172 |
+
)
|
| 1173 |
+
image_latents = (
|
| 1174 |
+
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1175 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1176 |
+
)
|
| 1177 |
+
fake_image_noise_sigma = (
|
| 1178 |
+
torch.rand(1, device=device, generator=generator) * (video_noise_sigma_max - video_noise_sigma_min)
|
| 1179 |
+
+ video_noise_sigma_min
|
| 1180 |
+
)
|
| 1181 |
+
fake_image_latents = (
|
| 1182 |
+
fake_image_noise_sigma * randn_tensor(fake_image_latents.shape, generator=generator, device=device)
|
| 1183 |
+
+ (1 - fake_image_noise_sigma) * fake_image_latents
|
| 1184 |
+
)
|
| 1185 |
+
|
| 1186 |
+
if video is not None:
|
| 1187 |
+
video = self.video_processor.preprocess_video(video, height=height, width=width)
|
| 1188 |
+
image_latents, video_latents = self.prepare_video_latents(
|
| 1189 |
+
video,
|
| 1190 |
+
latents_mean=latents_mean,
|
| 1191 |
+
latents_std=latents_std,
|
| 1192 |
+
latent_window_size=latent_window_size,
|
| 1193 |
+
dtype=torch.float32,
|
| 1194 |
+
device=device,
|
| 1195 |
+
generator=generator,
|
| 1196 |
+
latents=video_latents,
|
| 1197 |
+
)
|
| 1198 |
+
|
| 1199 |
+
if video_latents is not None and add_noise_to_video_latents:
|
| 1200 |
+
image_noise_sigma = (
|
| 1201 |
+
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
|
| 1202 |
+
+ image_noise_sigma_min
|
| 1203 |
+
)
|
| 1204 |
+
image_latents = (
|
| 1205 |
+
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1206 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1207 |
+
)
|
| 1208 |
+
|
| 1209 |
+
noisy_latents_chunks = []
|
| 1210 |
+
num_latent_chunks = video_latents.shape[2] // latent_window_size
|
| 1211 |
+
for i in range(num_latent_chunks):
|
| 1212 |
+
chunk_start = i * latent_window_size
|
| 1213 |
+
chunk_end = chunk_start + latent_window_size
|
| 1214 |
+
latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :]
|
| 1215 |
+
|
| 1216 |
+
chunk_frames = latent_chunk.shape[2]
|
| 1217 |
+
frame_sigmas = (
|
| 1218 |
+
torch.rand(chunk_frames, device=device, generator=generator)
|
| 1219 |
+
* (video_noise_sigma_max - video_noise_sigma_min)
|
| 1220 |
+
+ video_noise_sigma_min
|
| 1221 |
+
)
|
| 1222 |
+
frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1)
|
| 1223 |
+
|
| 1224 |
+
noisy_chunk = (
|
| 1225 |
+
frame_sigmas * randn_tensor(latent_chunk.shape, generator=generator, device=device)
|
| 1226 |
+
+ (1 - frame_sigmas) * latent_chunk
|
| 1227 |
+
)
|
| 1228 |
+
noisy_latents_chunks.append(noisy_chunk)
|
| 1229 |
+
video_latents = torch.cat(noisy_latents_chunks, dim=2)
|
| 1230 |
+
|
| 1231 |
+
# 5. Prepare latent variables
|
| 1232 |
+
num_channels_latents = self.transformer.config.in_channels
|
| 1233 |
+
window_num_frames = (latent_window_size - 1) * self.vae_scale_factor_temporal + 1
|
| 1234 |
+
num_latent_sections = max(1, (num_frames + window_num_frames - 1) // window_num_frames)
|
| 1235 |
+
total_generated_latent_frames = 0
|
| 1236 |
+
|
| 1237 |
+
if not is_keep_x0:
|
| 1238 |
+
history_sizes[-1] = history_sizes[-1] + 1
|
| 1239 |
+
history_latents = torch.zeros(
|
| 1240 |
+
batch_size,
|
| 1241 |
+
num_channels_latents,
|
| 1242 |
+
sum(history_sizes),
|
| 1243 |
+
height // self.vae_scale_factor_spatial,
|
| 1244 |
+
width // self.vae_scale_factor_spatial,
|
| 1245 |
+
device=device,
|
| 1246 |
+
dtype=torch.float32,
|
| 1247 |
+
)
|
| 1248 |
+
if fake_image_latents is not None:
|
| 1249 |
+
history_latents = torch.cat([history_latents, fake_image_latents], dim=2)
|
| 1250 |
+
total_generated_latent_frames += 1
|
| 1251 |
+
if video_latents is not None:
|
| 1252 |
+
history_frames = history_latents.shape[2]
|
| 1253 |
+
video_frames = video_latents.shape[2]
|
| 1254 |
+
if video_frames < history_frames:
|
| 1255 |
+
keep_frames = history_frames - video_frames
|
| 1256 |
+
history_latents = torch.cat([history_latents[:, :, :keep_frames, :, :], video_latents], dim=2)
|
| 1257 |
+
else:
|
| 1258 |
+
history_latents = video_latents
|
| 1259 |
+
total_generated_latent_frames += video_latents.shape[2]
|
| 1260 |
+
|
| 1261 |
+
# 6. Denoising loop
|
| 1262 |
+
all_sections_ode = []
|
| 1263 |
+
for k in range(num_latent_sections):
|
| 1264 |
+
if use_interpolate_prompt:
|
| 1265 |
+
assert num_latent_sections >= max(interpolate_cumulative_list)
|
| 1266 |
+
|
| 1267 |
+
current_interval_idx = 0
|
| 1268 |
+
for idx, cumulative_val in enumerate(interpolate_cumulative_list):
|
| 1269 |
+
if k < cumulative_val:
|
| 1270 |
+
current_interval_idx = idx
|
| 1271 |
+
break
|
| 1272 |
+
|
| 1273 |
+
if current_interval_idx == 0:
|
| 1274 |
+
prompt_embeds = all_prompt_embeds[0].unsqueeze(0)
|
| 1275 |
+
else:
|
| 1276 |
+
interval_start = interpolate_cumulative_list[current_interval_idx - 1]
|
| 1277 |
+
position_in_interval = k - interval_start
|
| 1278 |
+
|
| 1279 |
+
if position_in_interval < interpolation_steps:
|
| 1280 |
+
if interpolate_embeds is None or interpolate_interval_idx != current_interval_idx:
|
| 1281 |
+
interpolate_embeds = self.interpolate_prompt_embeds(
|
| 1282 |
+
prompt_embeds_1=all_prompt_embeds[current_interval_idx - 1].unsqueeze(0),
|
| 1283 |
+
prompt_embeds_2=all_prompt_embeds[current_interval_idx].unsqueeze(0),
|
| 1284 |
+
interpolation_steps=interpolation_steps,
|
| 1285 |
+
)
|
| 1286 |
+
interpolate_interval_idx = current_interval_idx
|
| 1287 |
+
|
| 1288 |
+
prompt_embeds = interpolate_embeds[position_in_interval]
|
| 1289 |
+
else:
|
| 1290 |
+
prompt_embeds = all_prompt_embeds[current_interval_idx].unsqueeze(0)
|
| 1291 |
+
else:
|
| 1292 |
+
prompt_embeds = all_prompt_embeds
|
| 1293 |
+
|
| 1294 |
+
is_first_section = k == 0
|
| 1295 |
+
is_second_section = k == 1
|
| 1296 |
+
if is_keep_x0:
|
| 1297 |
+
if is_first_section:
|
| 1298 |
+
history_sizes_first_section = [1] + history_sizes.copy()
|
| 1299 |
+
history_latents_first_section = torch.zeros(
|
| 1300 |
+
batch_size,
|
| 1301 |
+
num_channels_latents,
|
| 1302 |
+
sum(history_sizes_first_section),
|
| 1303 |
+
height // self.vae_scale_factor_spatial,
|
| 1304 |
+
width // self.vae_scale_factor_spatial,
|
| 1305 |
+
device=device,
|
| 1306 |
+
dtype=torch.float32,
|
| 1307 |
+
)
|
| 1308 |
+
if fake_image_latents is not None:
|
| 1309 |
+
history_latents_first_section = torch.cat(
|
| 1310 |
+
[history_latents_first_section, fake_image_latents], dim=2
|
| 1311 |
+
)
|
| 1312 |
+
if video_latents is not None:
|
| 1313 |
+
history_frames = history_latents_first_section.shape[2]
|
| 1314 |
+
video_frames = video_latents.shape[2]
|
| 1315 |
+
if video_frames < history_frames:
|
| 1316 |
+
keep_frames = history_frames - video_frames
|
| 1317 |
+
history_latents_first_section = torch.cat(
|
| 1318 |
+
[history_latents_first_section[:, :, :keep_frames, :, :], video_latents], dim=2
|
| 1319 |
+
)
|
| 1320 |
+
else:
|
| 1321 |
+
history_latents_first_section = video_latents
|
| 1322 |
+
|
| 1323 |
+
indices = torch.arange(0, sum([1, *history_sizes, latent_window_size]))
|
| 1324 |
+
(
|
| 1325 |
+
indices_prefix,
|
| 1326 |
+
indices_latents_history_long,
|
| 1327 |
+
indices_latents_history_mid,
|
| 1328 |
+
indices_latents_history_1x,
|
| 1329 |
+
indices_hidden_states,
|
| 1330 |
+
) = indices.split([1, *history_sizes, latent_window_size], dim=0)
|
| 1331 |
+
indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0)
|
| 1332 |
+
|
| 1333 |
+
latents_prefix, latents_history_long, latents_history_mid, latents_history_1x = (
|
| 1334 |
+
history_latents_first_section[:, :, -sum(history_sizes_first_section) :].split(
|
| 1335 |
+
history_sizes_first_section, dim=2
|
| 1336 |
+
)
|
| 1337 |
+
)
|
| 1338 |
+
if image_latents is not None:
|
| 1339 |
+
latents_prefix = image_latents
|
| 1340 |
+
latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2)
|
| 1341 |
+
else:
|
| 1342 |
+
indices = torch.arange(0, sum([1, *history_sizes, latent_window_size]))
|
| 1343 |
+
(
|
| 1344 |
+
indices_prefix,
|
| 1345 |
+
indices_latents_history_long,
|
| 1346 |
+
indices_latents_history_mid,
|
| 1347 |
+
indices_latents_history_1x,
|
| 1348 |
+
indices_hidden_states,
|
| 1349 |
+
) = indices.split([1, *history_sizes, latent_window_size], dim=0)
|
| 1350 |
+
indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0)
|
| 1351 |
+
|
| 1352 |
+
latents_prefix = image_latents
|
| 1353 |
+
latents_history_long, latents_history_mid, latents_history_1x = history_latents[
|
| 1354 |
+
:, :, -sum(history_sizes) :
|
| 1355 |
+
].split(history_sizes, dim=2)
|
| 1356 |
+
latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2)
|
| 1357 |
+
else:
|
| 1358 |
+
indices = torch.arange(0, sum([*history_sizes, latent_window_size]))
|
| 1359 |
+
(
|
| 1360 |
+
indices_latents_history_long,
|
| 1361 |
+
indices_latents_history_mid,
|
| 1362 |
+
indices_latents_history_short,
|
| 1363 |
+
indices_hidden_states,
|
| 1364 |
+
) = indices.split([*history_sizes, latent_window_size], dim=0)
|
| 1365 |
+
latents_history_long, latents_history_mid, latents_history_short = history_latents[
|
| 1366 |
+
:, :, -sum(history_sizes) :
|
| 1367 |
+
].split(history_sizes, dim=2)
|
| 1368 |
+
|
| 1369 |
+
latents = self.prepare_latents(
|
| 1370 |
+
batch_size,
|
| 1371 |
+
num_channels_latents,
|
| 1372 |
+
height,
|
| 1373 |
+
width,
|
| 1374 |
+
window_num_frames,
|
| 1375 |
+
dtype=torch.float32,
|
| 1376 |
+
device=device,
|
| 1377 |
+
generator=generator,
|
| 1378 |
+
latents=None,
|
| 1379 |
+
)
|
| 1380 |
+
|
| 1381 |
+
if not is_enable_stage2:
|
| 1382 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 1383 |
+
|
| 1384 |
+
if use_dynamic_shifting:
|
| 1385 |
+
sigmas = torch.linspace(
|
| 1386 |
+
0.999, 0.0, steps=num_inference_steps + 1, dtype=torch.float32, device=device
|
| 1387 |
+
)[:-1]
|
| 1388 |
+
sigmas = apply_schedule_shift(
|
| 1389 |
+
sigmas=sigmas,
|
| 1390 |
+
noise=latents,
|
| 1391 |
+
base_seq_len=self.scheduler.config.get("base_image_seq_len", 256),
|
| 1392 |
+
max_seq_len=self.scheduler.config.get("max_image_seq_len", 4096),
|
| 1393 |
+
base_shift=self.scheduler.config.get("base_shift", 0.5),
|
| 1394 |
+
max_shift=self.scheduler.config.get("max_shift", 1.15),
|
| 1395 |
+
time_shift_type=time_shift_type,
|
| 1396 |
+
)
|
| 1397 |
+
timesteps = sigmas * 1000.0 # rescale to [0, 1000.0)
|
| 1398 |
+
timesteps = timesteps.to(device)
|
| 1399 |
+
sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
|
| 1400 |
+
self.scheduler.timesteps = timesteps
|
| 1401 |
+
self.scheduler.sigmas = sigmas
|
| 1402 |
+
|
| 1403 |
+
timesteps = self.scheduler.timesteps
|
| 1404 |
+
|
| 1405 |
+
dmd_sigmas = None
|
| 1406 |
+
dmd_timesteps = None
|
| 1407 |
+
if use_dmd:
|
| 1408 |
+
dmd_sigmas = self.scheduler.sigmas.to(self.transformer.device)
|
| 1409 |
+
dmd_timesteps = self.scheduler.timesteps.to(self.transformer.device)
|
| 1410 |
+
|
| 1411 |
+
self._num_timesteps = len(timesteps)
|
| 1412 |
+
else:
|
| 1413 |
+
num_inference_steps = sum(stage2_num_inference_steps_list)
|
| 1414 |
+
|
| 1415 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 1416 |
+
if is_enable_stage2:
|
| 1417 |
+
latents, ode_stages_tensor = self.stage2_sample(
|
| 1418 |
+
is_first_section=is_first_section,
|
| 1419 |
+
latents=latents,
|
| 1420 |
+
stage2_num_stages=stage2_num_stages,
|
| 1421 |
+
stage2_num_inference_steps_list=stage2_num_inference_steps_list,
|
| 1422 |
+
prompt_embeds=prompt_embeds,
|
| 1423 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1424 |
+
guidance_scale=guidance_scale,
|
| 1425 |
+
indices_hidden_states=indices_hidden_states,
|
| 1426 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1427 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1428 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1429 |
+
latents_history_short=latents_history_short,
|
| 1430 |
+
latents_history_mid=latents_history_mid,
|
| 1431 |
+
latents_history_long=latents_history_long,
|
| 1432 |
+
attention_kwargs=attention_kwargs,
|
| 1433 |
+
device=device,
|
| 1434 |
+
transformer_dtype=transformer_dtype,
|
| 1435 |
+
scheduler_type=scheduler_type,
|
| 1436 |
+
use_dynamic_shifting=use_dynamic_shifting,
|
| 1437 |
+
time_shift_type=time_shift_type,
|
| 1438 |
+
generator=generator,
|
| 1439 |
+
# ------------ CFG Zero ------------
|
| 1440 |
+
use_cfg_zero_star=use_cfg_zero_star,
|
| 1441 |
+
use_zero_init=use_zero_init,
|
| 1442 |
+
zero_steps=zero_steps,
|
| 1443 |
+
# -------------- DMD --------------
|
| 1444 |
+
use_dmd=use_dmd,
|
| 1445 |
+
# ------------ Callback ------------
|
| 1446 |
+
callback_on_step_end=callback_on_step_end,
|
| 1447 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1448 |
+
progress_bar=progress_bar,
|
| 1449 |
+
)
|
| 1450 |
+
|
| 1451 |
+
all_sections_ode.append(ode_stages_tensor)
|
| 1452 |
+
else:
|
| 1453 |
+
latents = self.stage1_sample(
|
| 1454 |
+
latents=latents,
|
| 1455 |
+
prompt_embeds=prompt_embeds,
|
| 1456 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1457 |
+
timesteps=timesteps,
|
| 1458 |
+
guidance_scale=guidance_scale,
|
| 1459 |
+
indices_hidden_states=indices_hidden_states,
|
| 1460 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1461 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1462 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1463 |
+
latents_history_short=latents_history_short,
|
| 1464 |
+
latents_history_mid=latents_history_mid,
|
| 1465 |
+
latents_history_long=latents_history_long,
|
| 1466 |
+
attention_kwargs=attention_kwargs,
|
| 1467 |
+
device=device,
|
| 1468 |
+
transformer_dtype=transformer_dtype,
|
| 1469 |
+
generator=generator,
|
| 1470 |
+
# ------------ CFG Zero ------------
|
| 1471 |
+
use_cfg_zero_star=use_cfg_zero_star,
|
| 1472 |
+
use_zero_init=use_zero_init,
|
| 1473 |
+
zero_steps=zero_steps,
|
| 1474 |
+
# -------------- DMD --------------
|
| 1475 |
+
use_dmd=use_dmd,
|
| 1476 |
+
dmd_sigmas=dmd_sigmas,
|
| 1477 |
+
dmd_timesteps=dmd_timesteps,
|
| 1478 |
+
# ------------ Callback ------------
|
| 1479 |
+
callback_on_step_end=callback_on_step_end,
|
| 1480 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1481 |
+
progress_bar=progress_bar,
|
| 1482 |
+
)
|
| 1483 |
+
|
| 1484 |
+
if use_kv_cache:
|
| 1485 |
+
self.transformer.clear_kv_cache()
|
| 1486 |
+
|
| 1487 |
+
if use_adaptive_anti_drifting:
|
| 1488 |
+
current_mean, current_var = anti_drifting_helper.compute_latent_statistics(latents)
|
| 1489 |
+
anti_drifting_helper.update_global_statistics(current_mean, current_var)
|
| 1490 |
+
has_drift = anti_drifting_helper.detect_drift(current_mean, current_var)
|
| 1491 |
+
|
| 1492 |
+
if has_drift and k < num_latent_sections - 1:
|
| 1493 |
+
print(
|
| 1494 |
+
f"Drift detected at chunk {k + 1}/{num_latent_sections}. Applying Frame-Aware Corruption."
|
| 1495 |
+
)
|
| 1496 |
+
latents = anti_drifting_helper.apply_frame_aware_corruption(
|
| 1497 |
+
latents,
|
| 1498 |
+
corruption_strength=anti_drift_corruption_strength,
|
| 1499 |
+
generator=generator,
|
| 1500 |
+
)
|
| 1501 |
+
|
| 1502 |
+
if is_keep_x0 and (
|
| 1503 |
+
(is_first_section and image_latents is None) or (is_skip_first_section and is_second_section)
|
| 1504 |
+
):
|
| 1505 |
+
image_latents = latents[:, :, 0:1, :, :]
|
| 1506 |
+
|
| 1507 |
+
total_generated_latent_frames += latents.shape[2]
|
| 1508 |
+
history_latents = torch.cat([history_latents, latents], dim=2)
|
| 1509 |
+
|
| 1510 |
+
return all_sections_ode
|
Helios/_DEV/helios/pipelines/pipeline_output.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from diffusers.utils import BaseOutput
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass
|
| 10 |
+
class HeliosPipelineOutput(BaseOutput):
|
| 11 |
+
r"""
|
| 12 |
+
Output class for Helios pipelines.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
frames (`torch.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]):
|
| 16 |
+
List of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing
|
| 17 |
+
denoised PIL image sequences of length `num_frames.` It can also be a NumPy array or Torch tensor of shape
|
| 18 |
+
`(batch_size, num_frames, channels, height, width)`.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
frames: torch.T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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import List, Optional, Tuple, Union
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 9 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 10 |
+
from diffusers.utils import BaseOutput, deprecate
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class HeliosSchedulerOutput(BaseOutput):
|
| 15 |
+
"""
|
| 16 |
+
Output class for the scheduler's `step` function output.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
|
| 20 |
+
Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
|
| 21 |
+
denoising loop.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
prev_sample: torch.FloatTensor
|
| 25 |
+
model_outputs: torch.FloatTensor
|
| 26 |
+
last_sample: torch.FloatTensor
|
| 27 |
+
this_order: int
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class HeliosScheduler(SchedulerMixin, ConfigMixin):
|
| 31 |
+
"""
|
| 32 |
+
Euler scheduler.
|
| 33 |
+
|
| 34 |
+
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
|
| 35 |
+
methods the library implements for all schedulers such as loading and saving.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
num_train_timesteps (`int`, defaults to 1000):
|
| 39 |
+
The number of diffusion steps to train the model.
|
| 40 |
+
timestep_spacing (`str`, defaults to `"linspace"`):
|
| 41 |
+
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
|
| 42 |
+
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
|
| 43 |
+
shift (`float`, defaults to 1.0):
|
| 44 |
+
The shift value for the timestep schedule.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
_compatibles = []
|
| 48 |
+
order = 1
|
| 49 |
+
|
| 50 |
+
@register_to_config
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
num_train_timesteps: int = 1000,
|
| 54 |
+
shift: float = 1.0, # Following Stable diffusion 3,
|
| 55 |
+
stages: int = 3,
|
| 56 |
+
stage_range: List = [0, 1 / 3, 2 / 3, 1],
|
| 57 |
+
gamma: float = 1 / 3,
|
| 58 |
+
# For UniPC
|
| 59 |
+
thresholding: bool = False,
|
| 60 |
+
prediction_type: str = "flow_prediction",
|
| 61 |
+
solver_order: int = 2,
|
| 62 |
+
predict_x0: bool = True,
|
| 63 |
+
solver_type: str = "bh2",
|
| 64 |
+
lower_order_final: bool = True,
|
| 65 |
+
disable_corrector: List[int] = [],
|
| 66 |
+
solver_p: SchedulerMixin = None,
|
| 67 |
+
use_flow_sigmas: bool = True,
|
| 68 |
+
version: str = "v1",
|
| 69 |
+
):
|
| 70 |
+
self.version = version
|
| 71 |
+
self.timestep_ratios = {} # The timestep ratio for each stage
|
| 72 |
+
self.timesteps_per_stage = {} # The detailed timesteps per stage (fix max and min per stage)
|
| 73 |
+
self.sigmas_per_stage = {} # always uniform [1000, 0]
|
| 74 |
+
self.start_sigmas = {} # for start point / upsample renoise
|
| 75 |
+
self.end_sigmas = {} # for end point
|
| 76 |
+
self.ori_start_sigmas = {}
|
| 77 |
+
|
| 78 |
+
# self.init_sigmas()
|
| 79 |
+
self.init_sigmas_for_each_stage()
|
| 80 |
+
self.sigma_min = self.sigmas[-1].item()
|
| 81 |
+
self.sigma_max = self.sigmas[0].item()
|
| 82 |
+
self.gamma = gamma
|
| 83 |
+
|
| 84 |
+
if solver_type not in ["bh1", "bh2"]:
|
| 85 |
+
if solver_type in ["midpoint", "heun", "logrho"]:
|
| 86 |
+
self.register_to_config(solver_type="bh2")
|
| 87 |
+
else:
|
| 88 |
+
raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
|
| 89 |
+
|
| 90 |
+
self.predict_x0 = predict_x0
|
| 91 |
+
self.model_outputs = [None] * solver_order
|
| 92 |
+
self.timestep_list = [None] * solver_order
|
| 93 |
+
self.lower_order_nums = 0
|
| 94 |
+
self.disable_corrector = disable_corrector
|
| 95 |
+
self.solver_p = solver_p
|
| 96 |
+
self.last_sample = None
|
| 97 |
+
self._step_index = None
|
| 98 |
+
self._begin_index = None
|
| 99 |
+
|
| 100 |
+
def init_sigmas(self):
|
| 101 |
+
"""
|
| 102 |
+
initialize the global timesteps and sigmas
|
| 103 |
+
"""
|
| 104 |
+
num_train_timesteps = self.config.num_train_timesteps
|
| 105 |
+
shift = self.config.shift
|
| 106 |
+
|
| 107 |
+
alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps + 1)
|
| 108 |
+
sigmas = 1.0 - alphas
|
| 109 |
+
sigmas = np.flip(shift * sigmas / (1 + (shift - 1) * sigmas))[:-1].copy()
|
| 110 |
+
sigmas = torch.from_numpy(sigmas)
|
| 111 |
+
timesteps = (sigmas * num_train_timesteps).clone()
|
| 112 |
+
|
| 113 |
+
self._step_index = None
|
| 114 |
+
self._begin_index = None
|
| 115 |
+
self.timesteps = timesteps
|
| 116 |
+
self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication
|
| 117 |
+
|
| 118 |
+
def init_sigmas_for_each_stage(self):
|
| 119 |
+
"""
|
| 120 |
+
Init the timesteps for each stage
|
| 121 |
+
"""
|
| 122 |
+
self.init_sigmas()
|
| 123 |
+
|
| 124 |
+
stage_distance = []
|
| 125 |
+
stages = self.config.stages
|
| 126 |
+
training_steps = self.config.num_train_timesteps
|
| 127 |
+
stage_range = self.config.stage_range
|
| 128 |
+
|
| 129 |
+
# Init the start and end point of each stage
|
| 130 |
+
for i_s in range(stages):
|
| 131 |
+
# To decide the start and ends point
|
| 132 |
+
start_indice = int(stage_range[i_s] * training_steps)
|
| 133 |
+
start_indice = max(start_indice, 0)
|
| 134 |
+
end_indice = int(stage_range[i_s + 1] * training_steps)
|
| 135 |
+
end_indice = min(end_indice, training_steps)
|
| 136 |
+
start_sigma = self.sigmas[start_indice].item()
|
| 137 |
+
end_sigma = self.sigmas[end_indice].item() if end_indice < training_steps else 0.0
|
| 138 |
+
self.ori_start_sigmas[i_s] = start_sigma
|
| 139 |
+
|
| 140 |
+
if i_s != 0:
|
| 141 |
+
ori_sigma = 1 - start_sigma
|
| 142 |
+
gamma = self.config.gamma
|
| 143 |
+
corrected_sigma = (1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)) * ori_sigma
|
| 144 |
+
# corrected_sigma = 1 / (2 - ori_sigma) * ori_sigma
|
| 145 |
+
start_sigma = 1 - corrected_sigma
|
| 146 |
+
|
| 147 |
+
stage_distance.append(start_sigma - end_sigma)
|
| 148 |
+
self.start_sigmas[i_s] = start_sigma
|
| 149 |
+
self.end_sigmas[i_s] = end_sigma
|
| 150 |
+
|
| 151 |
+
if self.version == "v2":
|
| 152 |
+
new_start_indice = (
|
| 153 |
+
len(self.sigmas) - torch.searchsorted(self.sigmas.flip(0), start_sigma, right=True)
|
| 154 |
+
).item()
|
| 155 |
+
self.sigmas_per_stage[i_s] = self.sigmas[new_start_indice:end_indice]
|
| 156 |
+
self.timesteps_per_stage[i_s] = self.timesteps[new_start_indice:end_indice]
|
| 157 |
+
|
| 158 |
+
if self.version == "v2":
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
# Determine the ratio of each stage according to flow length
|
| 162 |
+
tot_distance = sum(stage_distance)
|
| 163 |
+
for i_s in range(stages):
|
| 164 |
+
if i_s == 0:
|
| 165 |
+
start_ratio = 0.0
|
| 166 |
+
else:
|
| 167 |
+
start_ratio = sum(stage_distance[:i_s]) / tot_distance
|
| 168 |
+
if i_s == stages - 1:
|
| 169 |
+
end_ratio = 0.9999999999999999
|
| 170 |
+
else:
|
| 171 |
+
end_ratio = sum(stage_distance[: i_s + 1]) / tot_distance
|
| 172 |
+
|
| 173 |
+
self.timestep_ratios[i_s] = (start_ratio, end_ratio)
|
| 174 |
+
|
| 175 |
+
# Determine the timesteps and sigmas for each stage
|
| 176 |
+
for i_s in range(stages):
|
| 177 |
+
timestep_ratio = self.timestep_ratios[i_s]
|
| 178 |
+
# timestep_max = self.timesteps[int(timestep_ratio[0] * training_steps)]
|
| 179 |
+
timestep_max = min(self.timesteps[int(timestep_ratio[0] * training_steps)], 999)
|
| 180 |
+
timestep_min = self.timesteps[min(int(timestep_ratio[1] * training_steps), training_steps - 1)]
|
| 181 |
+
timesteps = np.linspace(timestep_max, timestep_min, training_steps + 1)
|
| 182 |
+
self.timesteps_per_stage[i_s] = (
|
| 183 |
+
timesteps[:-1] if isinstance(timesteps, torch.Tensor) else torch.from_numpy(timesteps[:-1])
|
| 184 |
+
)
|
| 185 |
+
stage_sigmas = np.linspace(0.999, 0, training_steps + 1)
|
| 186 |
+
self.sigmas_per_stage[i_s] = torch.from_numpy(stage_sigmas[:-1])
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def step_index(self):
|
| 190 |
+
"""
|
| 191 |
+
The index counter for current timestep. It will increase 1 after each scheduler step.
|
| 192 |
+
"""
|
| 193 |
+
return self._step_index
|
| 194 |
+
|
| 195 |
+
@property
|
| 196 |
+
def begin_index(self):
|
| 197 |
+
"""
|
| 198 |
+
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
|
| 199 |
+
"""
|
| 200 |
+
return self._begin_index
|
| 201 |
+
|
| 202 |
+
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
|
| 203 |
+
def set_begin_index(self, begin_index: int = 0):
|
| 204 |
+
"""
|
| 205 |
+
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
begin_index (`int`):
|
| 209 |
+
The begin index for the scheduler.
|
| 210 |
+
"""
|
| 211 |
+
self._begin_index = begin_index
|
| 212 |
+
|
| 213 |
+
def _sigma_to_t(self, sigma):
|
| 214 |
+
return sigma * self.config.num_train_timesteps
|
| 215 |
+
|
| 216 |
+
def set_timesteps(
|
| 217 |
+
self,
|
| 218 |
+
num_inference_steps: int,
|
| 219 |
+
stage_index: int,
|
| 220 |
+
device: Union[str, torch.device] = None,
|
| 221 |
+
):
|
| 222 |
+
"""
|
| 223 |
+
Setting the timesteps and sigmas for each stage
|
| 224 |
+
"""
|
| 225 |
+
self.num_inference_steps = num_inference_steps
|
| 226 |
+
self.init_sigmas()
|
| 227 |
+
|
| 228 |
+
if self.version == "v1":
|
| 229 |
+
stage_timesteps = self.timesteps_per_stage[stage_index]
|
| 230 |
+
timestep_max = stage_timesteps[0].item()
|
| 231 |
+
timestep_min = stage_timesteps[-1].item()
|
| 232 |
+
|
| 233 |
+
timesteps = np.linspace(
|
| 234 |
+
timestep_max,
|
| 235 |
+
timestep_min,
|
| 236 |
+
num_inference_steps,
|
| 237 |
+
)
|
| 238 |
+
self.timesteps = torch.from_numpy(timesteps).to(device=device)
|
| 239 |
+
|
| 240 |
+
stage_sigmas = self.sigmas_per_stage[stage_index]
|
| 241 |
+
sigma_max = stage_sigmas[0].item()
|
| 242 |
+
sigma_min = stage_sigmas[-1].item()
|
| 243 |
+
|
| 244 |
+
ratios = np.linspace(sigma_max, sigma_min, num_inference_steps)
|
| 245 |
+
sigmas = torch.from_numpy(ratios).to(device=device)
|
| 246 |
+
self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
|
| 247 |
+
else:
|
| 248 |
+
total_steps = len(self.timesteps_per_stage[stage_index])
|
| 249 |
+
indices = np.linspace(0, total_steps - 1, num_inference_steps, dtype=int)
|
| 250 |
+
|
| 251 |
+
self.timesteps = self.timesteps_per_stage[stage_index][indices].to(device=device)
|
| 252 |
+
|
| 253 |
+
if stage_index == (self.config.stages - 1):
|
| 254 |
+
sigmas = self.sigmas_per_stage[stage_index][indices].to(device=device)
|
| 255 |
+
self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
|
| 256 |
+
else:
|
| 257 |
+
sigmas = self.sigmas_per_stage[stage_index][indices].to(device=device)
|
| 258 |
+
self.sigmas = torch.cat(
|
| 259 |
+
[sigmas, torch.tensor([self.ori_start_sigmas[stage_index + 1]], device=sigmas.device)]
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
self._step_index = None
|
| 263 |
+
self.reset_scheduler_history()
|
| 264 |
+
|
| 265 |
+
def index_for_timestep(self, timestep, schedule_timesteps=None):
|
| 266 |
+
if schedule_timesteps is None:
|
| 267 |
+
schedule_timesteps = self.timesteps
|
| 268 |
+
|
| 269 |
+
indices = (schedule_timesteps == timestep).nonzero()
|
| 270 |
+
|
| 271 |
+
# The sigma index that is taken for the **very** first `step`
|
| 272 |
+
# is always the second index (or the last index if there is only 1)
|
| 273 |
+
# This way we can ensure we don't accidentally skip a sigma in
|
| 274 |
+
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
|
| 275 |
+
pos = 1 if len(indices) > 1 else 0
|
| 276 |
+
|
| 277 |
+
return indices[pos].item()
|
| 278 |
+
|
| 279 |
+
def _init_step_index(self, timestep):
|
| 280 |
+
if self.begin_index is None:
|
| 281 |
+
if isinstance(timestep, torch.Tensor):
|
| 282 |
+
timestep = timestep.to(self.timesteps.device)
|
| 283 |
+
self._step_index = self.index_for_timestep(timestep)
|
| 284 |
+
else:
|
| 285 |
+
self._step_index = self._begin_index
|
| 286 |
+
|
| 287 |
+
def step(
|
| 288 |
+
self,
|
| 289 |
+
model_output: torch.FloatTensor,
|
| 290 |
+
timestep: Union[float, torch.FloatTensor] = None,
|
| 291 |
+
sample: torch.FloatTensor = None,
|
| 292 |
+
generator: Optional[torch.Generator] = None,
|
| 293 |
+
sigma: Optional[torch.FloatTensor] = None,
|
| 294 |
+
sigma_next: Optional[torch.FloatTensor] = None,
|
| 295 |
+
return_dict: bool = True,
|
| 296 |
+
) -> Union[HeliosSchedulerOutput, Tuple]:
|
| 297 |
+
"""
|
| 298 |
+
Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
|
| 299 |
+
process from the learned model outputs (most often the predicted noise).
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
model_output (`torch.FloatTensor`):
|
| 303 |
+
The direct output from learned diffusion model.
|
| 304 |
+
timestep (`float`):
|
| 305 |
+
The current discrete timestep in the diffusion chain.
|
| 306 |
+
sample (`torch.FloatTensor`):
|
| 307 |
+
A current instance of a sample created by the diffusion process.
|
| 308 |
+
generator (`torch.Generator`, *optional*):
|
| 309 |
+
A random number generator.
|
| 310 |
+
return_dict (`bool`):
|
| 311 |
+
Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or
|
| 312 |
+
tuple.
|
| 313 |
+
|
| 314 |
+
Returns:
|
| 315 |
+
[`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`:
|
| 316 |
+
If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is
|
| 317 |
+
returned, otherwise a tuple is returned where the first element is the sample tensor.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
assert (sigma is None) == (sigma_next is None), "sigma and sigma_next must both be None or both be not None"
|
| 321 |
+
|
| 322 |
+
if sigma is None and sigma_next is None:
|
| 323 |
+
if (
|
| 324 |
+
isinstance(timestep, int)
|
| 325 |
+
or isinstance(timestep, torch.IntTensor)
|
| 326 |
+
or isinstance(timestep, torch.LongTensor)
|
| 327 |
+
):
|
| 328 |
+
raise ValueError(
|
| 329 |
+
(
|
| 330 |
+
"Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
|
| 331 |
+
" `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
|
| 332 |
+
" one of the `scheduler.timesteps` as a timestep."
|
| 333 |
+
),
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
if self.step_index is None:
|
| 337 |
+
self._step_index = 0
|
| 338 |
+
|
| 339 |
+
# Upcast to avoid precision issues when computing prev_sample
|
| 340 |
+
sample = sample.to(torch.float32)
|
| 341 |
+
|
| 342 |
+
if sigma is None and sigma_next is None:
|
| 343 |
+
sigma = self.sigmas[self.step_index]
|
| 344 |
+
sigma_next = self.sigmas[self.step_index + 1]
|
| 345 |
+
|
| 346 |
+
prev_sample = sample + (sigma_next - sigma) * model_output
|
| 347 |
+
|
| 348 |
+
# Cast sample back to model compatible dtype
|
| 349 |
+
prev_sample = prev_sample.to(model_output.dtype)
|
| 350 |
+
|
| 351 |
+
# upon completion increase step index by one
|
| 352 |
+
self._step_index += 1
|
| 353 |
+
|
| 354 |
+
if not return_dict:
|
| 355 |
+
return (prev_sample,)
|
| 356 |
+
|
| 357 |
+
return HeliosSchedulerOutput(prev_sample=prev_sample)
|
| 358 |
+
|
| 359 |
+
# ---------------------------------- UniPC ----------------------------------
|
| 360 |
+
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._sigma_to_alpha_sigma_t
|
| 361 |
+
def _sigma_to_alpha_sigma_t(self, sigma):
|
| 362 |
+
if self.config.use_flow_sigmas:
|
| 363 |
+
alpha_t = 1 - sigma
|
| 364 |
+
sigma_t = torch.clamp(sigma, min=1e-8)
|
| 365 |
+
else:
|
| 366 |
+
alpha_t = 1 / ((sigma**2 + 1) ** 0.5)
|
| 367 |
+
sigma_t = sigma * alpha_t
|
| 368 |
+
|
| 369 |
+
return alpha_t, sigma_t
|
| 370 |
+
|
| 371 |
+
def convert_model_output(
|
| 372 |
+
self,
|
| 373 |
+
model_output: torch.Tensor,
|
| 374 |
+
*args,
|
| 375 |
+
sample: torch.Tensor = None,
|
| 376 |
+
sigma: torch.Tensor = None,
|
| 377 |
+
**kwargs,
|
| 378 |
+
) -> torch.Tensor:
|
| 379 |
+
r"""
|
| 380 |
+
Convert the model output to the corresponding type the UniPC algorithm needs.
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
model_output (`torch.Tensor`):
|
| 384 |
+
The direct output from the learned diffusion model.
|
| 385 |
+
timestep (`int`):
|
| 386 |
+
The current discrete timestep in the diffusion chain.
|
| 387 |
+
sample (`torch.Tensor`):
|
| 388 |
+
A current instance of a sample created by the diffusion process.
|
| 389 |
+
|
| 390 |
+
Returns:
|
| 391 |
+
`torch.Tensor`:
|
| 392 |
+
The converted model output.
|
| 393 |
+
"""
|
| 394 |
+
timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
|
| 395 |
+
if sample is None:
|
| 396 |
+
if len(args) > 1:
|
| 397 |
+
sample = args[1]
|
| 398 |
+
else:
|
| 399 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 400 |
+
if timestep is not None:
|
| 401 |
+
deprecate(
|
| 402 |
+
"timesteps",
|
| 403 |
+
"1.0.0",
|
| 404 |
+
"Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
flag = False
|
| 408 |
+
if sigma is None:
|
| 409 |
+
flag = True
|
| 410 |
+
sigma = self.sigmas[self.step_index]
|
| 411 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
|
| 412 |
+
|
| 413 |
+
if self.predict_x0:
|
| 414 |
+
if self.config.prediction_type == "epsilon":
|
| 415 |
+
x0_pred = (sample - sigma_t * model_output) / alpha_t
|
| 416 |
+
elif self.config.prediction_type == "sample":
|
| 417 |
+
x0_pred = model_output
|
| 418 |
+
elif self.config.prediction_type == "v_prediction":
|
| 419 |
+
x0_pred = alpha_t * sample - sigma_t * model_output
|
| 420 |
+
elif self.config.prediction_type == "flow_prediction":
|
| 421 |
+
if flag:
|
| 422 |
+
sigma_t = self.sigmas[self.step_index]
|
| 423 |
+
else:
|
| 424 |
+
sigma_t = sigma
|
| 425 |
+
x0_pred = sample - sigma_t * model_output
|
| 426 |
+
else:
|
| 427 |
+
raise ValueError(
|
| 428 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, "
|
| 429 |
+
"`v_prediction`, or `flow_prediction` for the UniPCMultistepScheduler."
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
if self.config.thresholding:
|
| 433 |
+
x0_pred = self._threshold_sample(x0_pred)
|
| 434 |
+
|
| 435 |
+
return x0_pred
|
| 436 |
+
else:
|
| 437 |
+
if self.config.prediction_type == "epsilon":
|
| 438 |
+
return model_output
|
| 439 |
+
elif self.config.prediction_type == "sample":
|
| 440 |
+
epsilon = (sample - alpha_t * model_output) / sigma_t
|
| 441 |
+
return epsilon
|
| 442 |
+
elif self.config.prediction_type == "v_prediction":
|
| 443 |
+
epsilon = alpha_t * model_output + sigma_t * sample
|
| 444 |
+
return epsilon
|
| 445 |
+
else:
|
| 446 |
+
raise ValueError(
|
| 447 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
|
| 448 |
+
" `v_prediction` for the UniPCMultistepScheduler."
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
def multistep_uni_p_bh_update(
|
| 452 |
+
self,
|
| 453 |
+
model_output: torch.Tensor,
|
| 454 |
+
*args,
|
| 455 |
+
sample: torch.Tensor = None,
|
| 456 |
+
order: int = None,
|
| 457 |
+
sigma: torch.Tensor = None,
|
| 458 |
+
sigma_next: torch.Tensor = None,
|
| 459 |
+
**kwargs,
|
| 460 |
+
) -> torch.Tensor:
|
| 461 |
+
"""
|
| 462 |
+
One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified.
|
| 463 |
+
|
| 464 |
+
Args:
|
| 465 |
+
model_output (`torch.Tensor`):
|
| 466 |
+
The direct output from the learned diffusion model at the current timestep.
|
| 467 |
+
prev_timestep (`int`):
|
| 468 |
+
The previous discrete timestep in the diffusion chain.
|
| 469 |
+
sample (`torch.Tensor`):
|
| 470 |
+
A current instance of a sample created by the diffusion process.
|
| 471 |
+
order (`int`):
|
| 472 |
+
The order of UniP at this timestep (corresponds to the *p* in UniPC-p).
|
| 473 |
+
|
| 474 |
+
Returns:
|
| 475 |
+
`torch.Tensor`:
|
| 476 |
+
The sample tensor at the previous timestep.
|
| 477 |
+
"""
|
| 478 |
+
prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None)
|
| 479 |
+
if sample is None:
|
| 480 |
+
if len(args) > 1:
|
| 481 |
+
sample = args[1]
|
| 482 |
+
else:
|
| 483 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 484 |
+
if order is None:
|
| 485 |
+
if len(args) > 2:
|
| 486 |
+
order = args[2]
|
| 487 |
+
else:
|
| 488 |
+
raise ValueError("missing `order` as a required keyword argument")
|
| 489 |
+
if prev_timestep is not None:
|
| 490 |
+
deprecate(
|
| 491 |
+
"prev_timestep",
|
| 492 |
+
"1.0.0",
|
| 493 |
+
"Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 494 |
+
)
|
| 495 |
+
model_output_list = self.model_outputs
|
| 496 |
+
|
| 497 |
+
s0 = self.timestep_list[-1]
|
| 498 |
+
m0 = model_output_list[-1]
|
| 499 |
+
x = sample
|
| 500 |
+
|
| 501 |
+
if self.solver_p:
|
| 502 |
+
x_t = self.solver_p.step(model_output, s0, x).prev_sample
|
| 503 |
+
return x_t
|
| 504 |
+
|
| 505 |
+
if sigma_next is None and sigma is None:
|
| 506 |
+
sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
|
| 507 |
+
else:
|
| 508 |
+
sigma_t, sigma_s0 = sigma_next, sigma
|
| 509 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 510 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 511 |
+
|
| 512 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 513 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 514 |
+
|
| 515 |
+
h = lambda_t - lambda_s0
|
| 516 |
+
device = sample.device
|
| 517 |
+
|
| 518 |
+
rks = []
|
| 519 |
+
D1s = []
|
| 520 |
+
for i in range(1, order):
|
| 521 |
+
si = self.step_index - i
|
| 522 |
+
mi = model_output_list[-(i + 1)]
|
| 523 |
+
alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
|
| 524 |
+
lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
|
| 525 |
+
rk = (lambda_si - lambda_s0) / h
|
| 526 |
+
rks.append(rk)
|
| 527 |
+
D1s.append((mi - m0) / rk)
|
| 528 |
+
|
| 529 |
+
rks.append(1.0)
|
| 530 |
+
rks = torch.tensor(rks, device=device)
|
| 531 |
+
|
| 532 |
+
R = []
|
| 533 |
+
b = []
|
| 534 |
+
|
| 535 |
+
hh = -h if self.predict_x0 else h
|
| 536 |
+
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
| 537 |
+
h_phi_k = h_phi_1 / hh - 1
|
| 538 |
+
|
| 539 |
+
factorial_i = 1
|
| 540 |
+
|
| 541 |
+
if self.config.solver_type == "bh1":
|
| 542 |
+
B_h = hh
|
| 543 |
+
elif self.config.solver_type == "bh2":
|
| 544 |
+
B_h = torch.expm1(hh)
|
| 545 |
+
else:
|
| 546 |
+
raise NotImplementedError()
|
| 547 |
+
|
| 548 |
+
for i in range(1, order + 1):
|
| 549 |
+
R.append(torch.pow(rks, i - 1))
|
| 550 |
+
b.append(h_phi_k * factorial_i / B_h)
|
| 551 |
+
factorial_i *= i + 1
|
| 552 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
| 553 |
+
|
| 554 |
+
R = torch.stack(R)
|
| 555 |
+
b = torch.tensor(b, device=device)
|
| 556 |
+
|
| 557 |
+
if len(D1s) > 0:
|
| 558 |
+
D1s = torch.stack(D1s, dim=1) # (B, K)
|
| 559 |
+
# for order 2, we use a simplified version
|
| 560 |
+
if order == 2:
|
| 561 |
+
rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device)
|
| 562 |
+
else:
|
| 563 |
+
rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]).to(device).to(x.dtype)
|
| 564 |
+
else:
|
| 565 |
+
D1s = None
|
| 566 |
+
|
| 567 |
+
if self.predict_x0:
|
| 568 |
+
x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
|
| 569 |
+
if D1s is not None:
|
| 570 |
+
pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s)
|
| 571 |
+
else:
|
| 572 |
+
pred_res = 0
|
| 573 |
+
x_t = x_t_ - alpha_t * B_h * pred_res
|
| 574 |
+
else:
|
| 575 |
+
x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
|
| 576 |
+
if D1s is not None:
|
| 577 |
+
pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s)
|
| 578 |
+
else:
|
| 579 |
+
pred_res = 0
|
| 580 |
+
x_t = x_t_ - sigma_t * B_h * pred_res
|
| 581 |
+
|
| 582 |
+
x_t = x_t.to(x.dtype)
|
| 583 |
+
return x_t
|
| 584 |
+
|
| 585 |
+
def multistep_uni_c_bh_update(
|
| 586 |
+
self,
|
| 587 |
+
this_model_output: torch.Tensor,
|
| 588 |
+
*args,
|
| 589 |
+
last_sample: torch.Tensor = None,
|
| 590 |
+
this_sample: torch.Tensor = None,
|
| 591 |
+
order: int = None,
|
| 592 |
+
sigma_before: torch.Tensor = None,
|
| 593 |
+
sigma: torch.Tensor = None,
|
| 594 |
+
**kwargs,
|
| 595 |
+
) -> torch.Tensor:
|
| 596 |
+
"""
|
| 597 |
+
One step for the UniC (B(h) version).
|
| 598 |
+
|
| 599 |
+
Args:
|
| 600 |
+
this_model_output (`torch.Tensor`):
|
| 601 |
+
The model outputs at `x_t`.
|
| 602 |
+
this_timestep (`int`):
|
| 603 |
+
The current timestep `t`.
|
| 604 |
+
last_sample (`torch.Tensor`):
|
| 605 |
+
The generated sample before the last predictor `x_{t-1}`.
|
| 606 |
+
this_sample (`torch.Tensor`):
|
| 607 |
+
The generated sample after the last predictor `x_{t}`.
|
| 608 |
+
order (`int`):
|
| 609 |
+
The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`.
|
| 610 |
+
|
| 611 |
+
Returns:
|
| 612 |
+
`torch.Tensor`:
|
| 613 |
+
The corrected sample tensor at the current timestep.
|
| 614 |
+
"""
|
| 615 |
+
this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None)
|
| 616 |
+
if last_sample is None:
|
| 617 |
+
if len(args) > 1:
|
| 618 |
+
last_sample = args[1]
|
| 619 |
+
else:
|
| 620 |
+
raise ValueError("missing `last_sample` as a required keyword argument")
|
| 621 |
+
if this_sample is None:
|
| 622 |
+
if len(args) > 2:
|
| 623 |
+
this_sample = args[2]
|
| 624 |
+
else:
|
| 625 |
+
raise ValueError("missing `this_sample` as a required keyword argument")
|
| 626 |
+
if order is None:
|
| 627 |
+
if len(args) > 3:
|
| 628 |
+
order = args[3]
|
| 629 |
+
else:
|
| 630 |
+
raise ValueError("missing `order` as a required keyword argument")
|
| 631 |
+
if this_timestep is not None:
|
| 632 |
+
deprecate(
|
| 633 |
+
"this_timestep",
|
| 634 |
+
"1.0.0",
|
| 635 |
+
"Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
model_output_list = self.model_outputs
|
| 639 |
+
|
| 640 |
+
m0 = model_output_list[-1]
|
| 641 |
+
x = last_sample
|
| 642 |
+
x_t = this_sample
|
| 643 |
+
model_t = this_model_output
|
| 644 |
+
|
| 645 |
+
if sigma_before is None and sigma is None:
|
| 646 |
+
sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1]
|
| 647 |
+
else:
|
| 648 |
+
sigma_t, sigma_s0 = sigma, sigma_before
|
| 649 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 650 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 651 |
+
|
| 652 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 653 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 654 |
+
|
| 655 |
+
h = lambda_t - lambda_s0
|
| 656 |
+
device = this_sample.device
|
| 657 |
+
|
| 658 |
+
rks = []
|
| 659 |
+
D1s = []
|
| 660 |
+
for i in range(1, order):
|
| 661 |
+
si = self.step_index - (i + 1)
|
| 662 |
+
mi = model_output_list[-(i + 1)]
|
| 663 |
+
alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
|
| 664 |
+
lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
|
| 665 |
+
rk = (lambda_si - lambda_s0) / h
|
| 666 |
+
rks.append(rk)
|
| 667 |
+
D1s.append((mi - m0) / rk)
|
| 668 |
+
|
| 669 |
+
rks.append(1.0)
|
| 670 |
+
rks = torch.tensor(rks, device=device)
|
| 671 |
+
|
| 672 |
+
R = []
|
| 673 |
+
b = []
|
| 674 |
+
|
| 675 |
+
hh = -h if self.predict_x0 else h
|
| 676 |
+
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
| 677 |
+
h_phi_k = h_phi_1 / hh - 1
|
| 678 |
+
|
| 679 |
+
factorial_i = 1
|
| 680 |
+
|
| 681 |
+
if self.config.solver_type == "bh1":
|
| 682 |
+
B_h = hh
|
| 683 |
+
elif self.config.solver_type == "bh2":
|
| 684 |
+
B_h = torch.expm1(hh)
|
| 685 |
+
else:
|
| 686 |
+
raise NotImplementedError()
|
| 687 |
+
|
| 688 |
+
for i in range(1, order + 1):
|
| 689 |
+
R.append(torch.pow(rks, i - 1))
|
| 690 |
+
b.append(h_phi_k * factorial_i / B_h)
|
| 691 |
+
factorial_i *= i + 1
|
| 692 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
| 693 |
+
|
| 694 |
+
R = torch.stack(R)
|
| 695 |
+
b = torch.tensor(b, device=device)
|
| 696 |
+
|
| 697 |
+
if len(D1s) > 0:
|
| 698 |
+
D1s = torch.stack(D1s, dim=1)
|
| 699 |
+
else:
|
| 700 |
+
D1s = None
|
| 701 |
+
|
| 702 |
+
# for order 1, we use a simplified version
|
| 703 |
+
if order == 1:
|
| 704 |
+
rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device)
|
| 705 |
+
else:
|
| 706 |
+
rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype)
|
| 707 |
+
|
| 708 |
+
if self.predict_x0:
|
| 709 |
+
x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
|
| 710 |
+
if D1s is not None:
|
| 711 |
+
corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
|
| 712 |
+
else:
|
| 713 |
+
corr_res = 0
|
| 714 |
+
D1_t = model_t - m0
|
| 715 |
+
x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t)
|
| 716 |
+
else:
|
| 717 |
+
x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
|
| 718 |
+
if D1s is not None:
|
| 719 |
+
corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
|
| 720 |
+
else:
|
| 721 |
+
corr_res = 0
|
| 722 |
+
D1_t = model_t - m0
|
| 723 |
+
x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t)
|
| 724 |
+
x_t = x_t.to(x.dtype)
|
| 725 |
+
return x_t
|
| 726 |
+
|
| 727 |
+
def step_unipc(
|
| 728 |
+
self,
|
| 729 |
+
model_output: torch.Tensor,
|
| 730 |
+
timestep: Union[int, torch.Tensor] = None,
|
| 731 |
+
sample: torch.Tensor = None,
|
| 732 |
+
return_dict: bool = True,
|
| 733 |
+
model_outputs: list = None,
|
| 734 |
+
timestep_list: list = None,
|
| 735 |
+
sigma_before: torch.Tensor = None,
|
| 736 |
+
sigma: torch.Tensor = None,
|
| 737 |
+
sigma_next: torch.Tensor = None,
|
| 738 |
+
cus_step_index: int = None,
|
| 739 |
+
cus_lower_order_num: int = None,
|
| 740 |
+
cus_this_order: int = None,
|
| 741 |
+
cus_last_sample: torch.Tensor = None,
|
| 742 |
+
) -> Union[HeliosSchedulerOutput, Tuple]:
|
| 743 |
+
"""
|
| 744 |
+
Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
|
| 745 |
+
the multistep UniPC.
|
| 746 |
+
|
| 747 |
+
Args:
|
| 748 |
+
model_output (`torch.Tensor`):
|
| 749 |
+
The direct output from learned diffusion model.
|
| 750 |
+
timestep (`int`):
|
| 751 |
+
The current discrete timestep in the diffusion chain.
|
| 752 |
+
sample (`torch.Tensor`):
|
| 753 |
+
A current instance of a sample created by the diffusion process.
|
| 754 |
+
return_dict (`bool`):
|
| 755 |
+
Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
|
| 756 |
+
|
| 757 |
+
Returns:
|
| 758 |
+
[`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
|
| 759 |
+
If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
|
| 760 |
+
tuple is returned where the first element is the sample tensor.
|
| 761 |
+
|
| 762 |
+
"""
|
| 763 |
+
# don't change
|
| 764 |
+
# print(len(self.model_outputs), len(self.timestep_list), self.disable_corrector, self.solver_p, self._begin_index)
|
| 765 |
+
|
| 766 |
+
if self.num_inference_steps is None:
|
| 767 |
+
raise ValueError(
|
| 768 |
+
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
if cus_step_index is None:
|
| 772 |
+
if self.step_index is None:
|
| 773 |
+
self._step_index = 0
|
| 774 |
+
else:
|
| 775 |
+
self._step_index = cus_step_index
|
| 776 |
+
|
| 777 |
+
if cus_lower_order_num is not None:
|
| 778 |
+
self.lower_order_nums = cus_lower_order_num
|
| 779 |
+
|
| 780 |
+
if cus_this_order is not None:
|
| 781 |
+
self.this_order = cus_this_order
|
| 782 |
+
|
| 783 |
+
if cus_last_sample is not None:
|
| 784 |
+
self.last_sample = cus_last_sample
|
| 785 |
+
|
| 786 |
+
use_corrector = (
|
| 787 |
+
self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
# Convert model output using the proper conversion method
|
| 791 |
+
model_output_convert = self.convert_model_output(model_output, sample=sample, sigma=sigma)
|
| 792 |
+
|
| 793 |
+
if model_outputs is not None and timestep_list is not None:
|
| 794 |
+
self.model_outputs = model_outputs[:-1]
|
| 795 |
+
self.timestep_list = timestep_list[:-1]
|
| 796 |
+
|
| 797 |
+
# print("1", self.step_index, self.timestep_list)
|
| 798 |
+
|
| 799 |
+
if use_corrector:
|
| 800 |
+
sample = self.multistep_uni_c_bh_update(
|
| 801 |
+
this_model_output=model_output_convert,
|
| 802 |
+
last_sample=self.last_sample,
|
| 803 |
+
this_sample=sample,
|
| 804 |
+
order=self.this_order,
|
| 805 |
+
sigma_before=sigma_before,
|
| 806 |
+
sigma=sigma,
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
if model_outputs is not None and timestep_list is not None:
|
| 810 |
+
model_outputs[-1] = model_output_convert
|
| 811 |
+
self.model_outputs = model_outputs[1:]
|
| 812 |
+
self.timestep_list = timestep_list[1:]
|
| 813 |
+
else:
|
| 814 |
+
for i in range(self.config.solver_order - 1):
|
| 815 |
+
self.model_outputs[i] = self.model_outputs[i + 1]
|
| 816 |
+
self.timestep_list[i] = self.timestep_list[i + 1]
|
| 817 |
+
self.model_outputs[-1] = model_output_convert
|
| 818 |
+
self.timestep_list[-1] = timestep
|
| 819 |
+
|
| 820 |
+
if self.config.lower_order_final:
|
| 821 |
+
this_order = min(self.config.solver_order, len(self.timesteps) - self.step_index)
|
| 822 |
+
else:
|
| 823 |
+
this_order = self.config.solver_order
|
| 824 |
+
self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep
|
| 825 |
+
assert self.this_order > 0
|
| 826 |
+
|
| 827 |
+
# change
|
| 828 |
+
# print("2", self.step_index, self.timestep_list, self.lower_order_nums, self.this_order, "\n")
|
| 829 |
+
# print(self._step_index, self.lower_order_nums, use_corrector, self.this_order, self.lower_order_nums)
|
| 830 |
+
# 0 1 False 1 1
|
| 831 |
+
# 1 2 True 2 2
|
| 832 |
+
# 2 2 True 2 2
|
| 833 |
+
# 3 2 True 2 2
|
| 834 |
+
# 4 2 True 2 2
|
| 835 |
+
# 5 2 True 2 2
|
| 836 |
+
# 6 2 True 2 2
|
| 837 |
+
# 7 2 True 2 2
|
| 838 |
+
# 8 2 True 2 2
|
| 839 |
+
# 9 2 True 1 2
|
| 840 |
+
|
| 841 |
+
self.last_sample = sample
|
| 842 |
+
prev_sample = self.multistep_uni_p_bh_update(
|
| 843 |
+
model_output=model_output, # pass the original non-converted model output, in case solver-p is used
|
| 844 |
+
sample=sample,
|
| 845 |
+
order=self.this_order,
|
| 846 |
+
sigma=sigma,
|
| 847 |
+
sigma_next=sigma_next,
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
if cus_lower_order_num is None:
|
| 851 |
+
if self.lower_order_nums < self.config.solver_order:
|
| 852 |
+
self.lower_order_nums += 1
|
| 853 |
+
|
| 854 |
+
# upon completion increase step index by one
|
| 855 |
+
if cus_step_index is None:
|
| 856 |
+
self._step_index += 1
|
| 857 |
+
|
| 858 |
+
if not return_dict:
|
| 859 |
+
return (prev_sample, model_outputs, self.last_sample, self.this_order)
|
| 860 |
+
|
| 861 |
+
return HeliosSchedulerOutput(
|
| 862 |
+
prev_sample=prev_sample,
|
| 863 |
+
model_outputs=model_outputs,
|
| 864 |
+
last_sample=self.last_sample,
|
| 865 |
+
this_order=self.this_order,
|
| 866 |
+
)
|
| 867 |
+
|
| 868 |
+
def reset_scheduler_history(self):
|
| 869 |
+
self.model_outputs = [None] * self.config.solver_order
|
| 870 |
+
self.timestep_list = [None] * self.config.solver_order
|
| 871 |
+
self.lower_order_nums = 0
|
| 872 |
+
self.disable_corrector = self.config.disable_corrector
|
| 873 |
+
self.solver_p = self.config.solver_p
|
| 874 |
+
self.last_sample = None
|
| 875 |
+
self._step_index = None
|
| 876 |
+
self._begin_index = None
|
| 877 |
+
|
| 878 |
+
def __len__(self):
|
| 879 |
+
return self.config.num_train_timesteps
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
if __name__ == "__main__":
|
| 883 |
+
device = "cuda"
|
| 884 |
+
|
| 885 |
+
# ---------------------- For dynamic shifting ----------------------
|
| 886 |
+
from examples.scheduling_unipc_multistep_latest import UniPCMultistepScheduler
|
| 887 |
+
|
| 888 |
+
scheduler_official = UniPCMultistepScheduler.from_pretrained("BestWishYsh/Helios-Base", subfolder="scheduler")
|
| 889 |
+
scheduler_official.set_timesteps(num_inference_steps=50)
|
| 890 |
+
scheduler_official.timesteps
|
| 891 |
+
scheduler_official.sigmas
|
| 892 |
+
|
| 893 |
+
# # Official
|
| 894 |
+
# from scheduling_flow_match_euler_discrete_official import FlowMatchEulerDiscreteScheduler
|
| 895 |
+
# scheduler_official = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=3.0)
|
| 896 |
+
# scheduler_official.set_timesteps(num_inference_steps=50, sigmas=None)
|
| 897 |
+
# scheduler_official.timesteps
|
| 898 |
+
# scheduler_official.sigmas
|
| 899 |
+
|
| 900 |
+
# import sys
|
| 901 |
+
# sys.path.append("../../")
|
| 902 |
+
# from helios.utils.utils_helios_base import apply_schedule_shift
|
| 903 |
+
|
| 904 |
+
# sigmas = apply_schedule_shift(scheduler_official.sigmas, torch.ones([2, 16, 21, 48, 80]), mu=3)
|
| 905 |
+
# timesteps = sigmas[:-1] * 1000.0
|
| 906 |
+
|
| 907 |
+
# import copy
|
| 908 |
+
# from diffusers.training_utils import compute_density_for_timestep_sampling
|
| 909 |
+
|
| 910 |
+
# def get_sigmas(timesteps, n_dim=4, device="cpu", dtype=torch.float32):
|
| 911 |
+
# sigmas = noise_scheduler_copy.sigmas.to(device=device, dtype=dtype)
|
| 912 |
+
# schedule_timesteps = noise_scheduler_copy.timesteps.to(device)
|
| 913 |
+
# timesteps = timesteps.to(device)
|
| 914 |
+
# step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 915 |
+
# sigma = sigmas[step_indices].flatten()
|
| 916 |
+
# while len(sigma.shape) < n_dim:
|
| 917 |
+
# sigma = sigma.unsqueeze(-1)
|
| 918 |
+
# return sigma
|
| 919 |
+
|
| 920 |
+
# noise_scheduler_copy = copy.deepcopy(scheduler_official)
|
| 921 |
+
|
| 922 |
+
# # Sample noise that we'll add to the latents
|
| 923 |
+
# model_input = torch.ones([2, 16, 9, 88, 68])
|
| 924 |
+
# noise = torch.randn_like(model_input)
|
| 925 |
+
# bsz = model_input.shape[0]
|
| 926 |
+
|
| 927 |
+
# # Sample a random timestep for each image
|
| 928 |
+
# # for weighting schemes where we sample timesteps non-uniformly
|
| 929 |
+
# u = compute_density_for_timestep_sampling(
|
| 930 |
+
# weighting_scheme="logit_normal", batch_size=bsz, logit_mean=0.0, logit_std=1.0, mode_scale=1.29
|
| 931 |
+
# )
|
| 932 |
+
# indices = (u * noise_scheduler_copy.config.num_train_timesteps).long()
|
| 933 |
+
# timesteps = noise_scheduler_copy.timesteps[indices].to(device=model_input.device)
|
| 934 |
+
|
| 935 |
+
# # Add noise according to flow matching.
|
| 936 |
+
# # zt = (1 - texp) * x + texp * z1
|
| 937 |
+
# sigmas = get_sigmas(timesteps, n_dim=model_input.ndim, dtype=model_input.dtype)
|
| 938 |
+
|
| 939 |
+
# import sys
|
| 940 |
+
# sys.path.append("../../")
|
| 941 |
+
# from helios.utils.utils_helios_base import apply_schedule_shift
|
| 942 |
+
|
| 943 |
+
# sigmas = apply_schedule_shift(sigmas, noise) # torch.Size([2, 1, 1, 1, 1])
|
| 944 |
+
# timesteps = sigmas * 1000.0 # rescale to [0, 1000.0)
|
| 945 |
+
# while timesteps.ndim > 1:
|
| 946 |
+
# timesteps = timesteps.squeeze(-1)
|
| 947 |
+
# ---------------------- For dynamic shifting ----------------------
|
| 948 |
+
|
| 949 |
+
# ---------------------- For timestep shifting ----------------------
|
| 950 |
+
stages = 3
|
| 951 |
+
timestep_shift = 1.0
|
| 952 |
+
stage_range = [0, 1 / 3, 2 / 3, 1]
|
| 953 |
+
scheduler_gamma = 1 / 3
|
| 954 |
+
version = "v1"
|
| 955 |
+
scheduler = HeliosScheduler(
|
| 956 |
+
shift=timestep_shift, stages=stages, stage_range=stage_range, gamma=scheduler_gamma, version=version
|
| 957 |
+
)
|
| 958 |
+
print(
|
| 959 |
+
f"The start sigmas and end sigmas of each stage is Start: {scheduler.start_sigmas}, End: {scheduler.end_sigmas}, Ori_start: {scheduler.ori_start_sigmas}"
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
i_s = 1
|
| 963 |
+
stage2_num_inference_steps_list = [3, 3, 3]
|
| 964 |
+
scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s)
|
| 965 |
+
scheduler.timesteps.to(dtype=torch.float32)
|
| 966 |
+
scheduler.sigmas.to(dtype=torch.float32)
|
| 967 |
+
|
| 968 |
+
# stages = 2
|
| 969 |
+
# timestep_shift = 3.0
|
| 970 |
+
# stage_range = [0, 1 / 2, 1]
|
| 971 |
+
# scheduler_gamma = 1 / 3
|
| 972 |
+
# version = "v2"
|
| 973 |
+
# scheduler = HeliosScheduler(
|
| 974 |
+
# shift=timestep_shift, stages=stages, stage_range=stage_range, gamma=scheduler_gamma, version=version
|
| 975 |
+
# )
|
| 976 |
+
# print(
|
| 977 |
+
# f"The start sigmas and end sigmas of each stage is Start: {scheduler.start_sigmas}, End: {scheduler.end_sigmas}, Ori_start: {scheduler.ori_start_sigmas}"
|
| 978 |
+
# )
|
| 979 |
+
|
| 980 |
+
# i_s = 1
|
| 981 |
+
# stage2_num_inference_steps_list = [10, 10]
|
| 982 |
+
# scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s)
|
| 983 |
+
# scheduler.timesteps.to(dtype=torch.float32)
|
| 984 |
+
# scheduler.sigmas.to(dtype=torch.float32)
|
| 985 |
+
|
| 986 |
+
# scheduler.timesteps_per_stage[0]
|
| 987 |
+
# scheduler.sigmas_per_stage[0]
|
| 988 |
+
# shift1: (999, 743.5120) -> (743.2563, 385.9723) -> (385.6146, 1.3846)
|
| 989 |
+
# shift3: (999, 957.3958) -> (957.3542, 828.9170) -> (828.7885, 3.8198)
|
| 990 |
+
|
| 991 |
+
# timesteps_1 = np.linspace(1, 1000 - 1, 1000, dtype=np.float32)[::-1].copy()
|
| 992 |
+
# timesteps_1 = torch.from_numpy(timesteps_1).to(dtype=torch.float32)
|
| 993 |
+
# sigmas_1 = timesteps_1 / 1000
|
| 994 |
+
# sigmas_1 = apply_schedule_shift(sigmas_1, torch.ones([2, 16, 21, 48, 80]), mu=3)
|
| 995 |
+
# timesteps_2 = sigmas_1 * 1000
|
| 996 |
+
|
| 997 |
+
# import pdb;pdb.set_trace()
|
| 998 |
+
# temp_sigmas = apply_schedule_shift(scheduler.timesteps / 1000, torch.ones([2, 16, 21, 48, 80]), mu=3)
|
| 999 |
+
# temp_timesteps = temp_sigmas * 1000
|
| 1000 |
+
# while temp_timesteps.ndim > 1:
|
| 1001 |
+
# temp_timesteps = temp_timesteps.squeeze(-1)
|
| 1002 |
+
# temp_timesteps = temp_timesteps[:-1]
|
| 1003 |
+
|
| 1004 |
+
# # very important here!
|
| 1005 |
+
# timesteps = temp_timesteps
|
| 1006 |
+
# # self.scheduler.sigmas = temp_sigmas
|
| 1007 |
+
# scheduler.timesteps = temp_timesteps
|
| 1008 |
+
|
| 1009 |
+
# ---------------------- For timestep shifting ----------------------
|
| 1010 |
+
|
| 1011 |
+
# ---------------------- For dynamic shifting ----------------------
|
| 1012 |
+
|
| 1013 |
+
# ---------------------- For per step sigmas & timesteps ----------------------
|
| 1014 |
+
# scheduler = HeliosScheduler(shift=3.0, stages=stages, stage_range=stage_range, gamma=scheduler_gamma)
|
| 1015 |
+
# stage2_num_inference_steps_list = [10, 10, 10]
|
| 1016 |
+
# i_s = 0
|
| 1017 |
+
# scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s)
|
| 1018 |
+
# scheduler.timesteps_per_stage[0]
|
| 1019 |
+
# scheduler.sigmas_per_stage[0]
|
| 1020 |
+
# scheduler.timesteps
|
| 1021 |
+
# scheduler.sigmas
|
| 1022 |
+
# ---------------------- For per step sigmas & timesteps ----------------------
|
| 1023 |
+
|
| 1024 |
+
# ---------------------- For Custom step ----------------------
|
| 1025 |
+
# timesteps = scheduler.timesteps
|
| 1026 |
+
# noise_pred = torch.randn([2, 16, 10, 48, 80], device=device)
|
| 1027 |
+
# latents = torch.randn([2, 16, 10, 48, 80], device=device)
|
| 1028 |
+
# for i, t in enumerate(timesteps):
|
| 1029 |
+
# print(i, t)
|
| 1030 |
+
# # latents = scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 1031 |
+
# latents = scheduler.step_custom_unipc(noise_pred, t, latents, return_dict=False)[0]
|
| 1032 |
+
|
| 1033 |
+
# def upsample_tensor(tensor, scale_factor=2):
|
| 1034 |
+
# return torch.nn.functional.interpolate(
|
| 1035 |
+
# tensor, scale_factor=scale_factor, mode="trilinear", align_corners=False
|
| 1036 |
+
# )
|
| 1037 |
+
|
| 1038 |
+
# stage2_num_inference_steps_list = [10, 10, 10]
|
| 1039 |
+
# noise_pred = torch.randn([2, 16, 10, 12, 20], device=device)
|
| 1040 |
+
# latents = torch.randn([2, 16, 10, 12, 20], device=device)
|
| 1041 |
+
# for stage, num_steps in enumerate(stage2_num_inference_steps_list):
|
| 1042 |
+
# print(f"stage: {stage}, num_steps: {num_steps}")
|
| 1043 |
+
# if stage > 0:
|
| 1044 |
+
# latents = upsample_tensor(latents, scale_factor=2)
|
| 1045 |
+
# noise_pred = upsample_tensor(noise_pred, scale_factor=2)
|
| 1046 |
+
|
| 1047 |
+
# scheduler.set_timesteps(num_steps, stage)
|
| 1048 |
+
# timesteps = scheduler.timesteps
|
| 1049 |
+
|
| 1050 |
+
# print(f"Timesteps for stage {stage + 1}: {timesteps}")
|
| 1051 |
+
|
| 1052 |
+
# for i, t in enumerate(timesteps):
|
| 1053 |
+
# # print(i, t, latents.shape)
|
| 1054 |
+
# # latents = scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 1055 |
+
# latents = scheduler.step_unipc(noise_pred, t, latents, return_dict=False)[0]
|
| 1056 |
+
# ---------------------- For Custom step ----------------------
|
Helios/_DEV/helios/utils/create_ema_zero3.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
from typing import Any, Dict, Iterable, Optional, Union
|
| 6 |
+
|
| 7 |
+
from huggingface_hub import save_torch_state_dict
|
| 8 |
+
|
| 9 |
+
from diffusers.utils import (
|
| 10 |
+
deprecate,
|
| 11 |
+
is_torchvision_available,
|
| 12 |
+
is_transformers_available,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if is_transformers_available():
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
if is_torchvision_available():
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
import deepspeed
|
| 23 |
+
import torch
|
| 24 |
+
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _z3_params_to_fetch(param_list):
|
| 28 |
+
return [p for p in param_list if hasattr(p, "ds_id") and p.ds_status == ZeroParamStatus.NOT_AVAILABLE]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Adapted from diffusers-style ema https://github.com/huggingface/diffusers/blob/main/src/diffusers/training_utils.py#L263
|
| 32 |
+
class EMAModel_Zero3:
|
| 33 |
+
"""
|
| 34 |
+
Exponential Moving Average of models weights
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
model: torch.nn.Module,
|
| 40 |
+
decay: float = 0.9999,
|
| 41 |
+
min_decay: float = 0.0,
|
| 42 |
+
update_after_step: int = 0,
|
| 43 |
+
use_ema_warmup: bool = False,
|
| 44 |
+
inv_gamma: Union[float, int] = 1.0,
|
| 45 |
+
power: Union[float, int] = 2 / 3,
|
| 46 |
+
model_cls: Optional[Any] = None,
|
| 47 |
+
model_config: Dict[str, Any] = None,
|
| 48 |
+
weight_file_prefix: Optional[str] = "",
|
| 49 |
+
**kwargs,
|
| 50 |
+
):
|
| 51 |
+
"""
|
| 52 |
+
Args:
|
| 53 |
+
parameters (Iterable[torch.nn.Parameter]): The parameters to track.
|
| 54 |
+
decay (float): The decay factor for the exponential moving average.
|
| 55 |
+
min_decay (float): The minimum decay factor for the exponential moving average.
|
| 56 |
+
update_after_step (int): The number of steps to wait before starting to update the EMA weights.
|
| 57 |
+
use_ema_warmup (bool): Whether to use EMA warmup.
|
| 58 |
+
inv_gamma (float):
|
| 59 |
+
Inverse multiplicative factor of EMA warmup. Default: 1. Only used if `use_ema_warmup` is True.
|
| 60 |
+
power (float): Exponential factor of EMA warmup. Default: 2/3. Only used if `use_ema_warmup` is True.
|
| 61 |
+
device (Optional[Union[str, torch.device]]): The device to store the EMA weights on. If None, the EMA
|
| 62 |
+
weights will be stored on CPU.
|
| 63 |
+
|
| 64 |
+
@crowsonkb's notes on EMA Warmup:
|
| 65 |
+
If gamma=1 and power=1, implements a simple average. gamma=1, power=2/3 are good values for models you plan
|
| 66 |
+
to train for a million or more steps (reaches decay factor 0.999 at 31.6K steps, 0.9999 at 1M steps),
|
| 67 |
+
gamma=1, power=3/4 for models you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999
|
| 68 |
+
at 215.4k steps).
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
self.model = model
|
| 72 |
+
|
| 73 |
+
if kwargs.get("max_value", None) is not None:
|
| 74 |
+
deprecation_message = "The `max_value` argument is deprecated. Please use `decay` instead."
|
| 75 |
+
deprecate("max_value", "1.0.0", deprecation_message, standard_warn=False)
|
| 76 |
+
decay = kwargs["max_value"]
|
| 77 |
+
|
| 78 |
+
if kwargs.get("min_value", None) is not None:
|
| 79 |
+
deprecation_message = "The `min_value` argument is deprecated. Please use `min_decay` instead."
|
| 80 |
+
deprecate("min_value", "1.0.0", deprecation_message, standard_warn=False)
|
| 81 |
+
min_decay = kwargs["min_value"]
|
| 82 |
+
|
| 83 |
+
if kwargs.get("device", None) is not None:
|
| 84 |
+
deprecation_message = "The `device` argument is deprecated. Please use `to` instead."
|
| 85 |
+
deprecate("device", "1.0.0", deprecation_message, standard_warn=False)
|
| 86 |
+
self.to(device=kwargs["device"])
|
| 87 |
+
|
| 88 |
+
self.temp_stored_params = None
|
| 89 |
+
|
| 90 |
+
self.decay = decay
|
| 91 |
+
self.min_decay = min_decay
|
| 92 |
+
self.update_after_step = update_after_step
|
| 93 |
+
self.use_ema_warmup = use_ema_warmup
|
| 94 |
+
self.inv_gamma = inv_gamma
|
| 95 |
+
self.power = power
|
| 96 |
+
self.optimization_step = 0
|
| 97 |
+
self.cur_decay_value = None # set in `step()`
|
| 98 |
+
|
| 99 |
+
self.model_cls = model_cls
|
| 100 |
+
self.model_config = model_config
|
| 101 |
+
|
| 102 |
+
self.weight_file_prefix = weight_file_prefix
|
| 103 |
+
|
| 104 |
+
@classmethod
|
| 105 |
+
def extract_ema_kwargs(cls, kwargs):
|
| 106 |
+
"""
|
| 107 |
+
Extracts the EMA kwargs from the kwargs of a class method.
|
| 108 |
+
"""
|
| 109 |
+
ema_kwargs = {}
|
| 110 |
+
for key in [
|
| 111 |
+
"decay",
|
| 112 |
+
"min_decay",
|
| 113 |
+
"optimization_step",
|
| 114 |
+
"update_after_step",
|
| 115 |
+
"use_ema_warmup",
|
| 116 |
+
"inv_gamma",
|
| 117 |
+
"power",
|
| 118 |
+
]:
|
| 119 |
+
if kwargs.get(key, None) is not None:
|
| 120 |
+
ema_kwargs[key] = kwargs.pop(key)
|
| 121 |
+
return ema_kwargs
|
| 122 |
+
|
| 123 |
+
@classmethod
|
| 124 |
+
def from_pretrained(cls, path, model_cls) -> "EMAModel_Zero3":
|
| 125 |
+
config = model_cls.load_config(path)
|
| 126 |
+
ema_kwargs = cls.extract_ema_kwargs(config)
|
| 127 |
+
model = model_cls.from_pretrained(path)
|
| 128 |
+
|
| 129 |
+
ema_model = cls(model, model_cls=model_cls, model_config=config)
|
| 130 |
+
|
| 131 |
+
ema_model.load_state_dict(ema_kwargs)
|
| 132 |
+
return ema_model
|
| 133 |
+
|
| 134 |
+
def save_pretrained(self, path):
|
| 135 |
+
if self.model_cls is None:
|
| 136 |
+
raise ValueError("`save_pretrained` can only be used if `model_cls` was defined at __init__.")
|
| 137 |
+
|
| 138 |
+
if self.model_config is None:
|
| 139 |
+
raise ValueError("`save_pretrained` can only be used if `model_config` was defined at __init__.")
|
| 140 |
+
|
| 141 |
+
rank = int(os.getenv("RANK", "0"))
|
| 142 |
+
state_dict = self.state_dict()
|
| 143 |
+
state_dict.pop("model")
|
| 144 |
+
|
| 145 |
+
model_to_save = self.model.module if hasattr(self.model, "module") else self.model
|
| 146 |
+
model_state_dict = {}
|
| 147 |
+
for k, v in model_to_save.named_parameters():
|
| 148 |
+
# only gather z3 params
|
| 149 |
+
params_to_fetch = _z3_params_to_fetch([v])
|
| 150 |
+
with deepspeed.zero.GatheredParameters(params_to_fetch, enabled=len(params_to_fetch) > 0):
|
| 151 |
+
vv = v.data.cpu()
|
| 152 |
+
if rank == 0:
|
| 153 |
+
model_state_dict[k] = vv
|
| 154 |
+
|
| 155 |
+
if rank == 0:
|
| 156 |
+
os.makedirs(path, exist_ok=True)
|
| 157 |
+
print(f"state_dict, {state_dict.keys()}")
|
| 158 |
+
import time
|
| 159 |
+
|
| 160 |
+
t_start = time.perf_counter()
|
| 161 |
+
print(f"[{t_start:.4f}] 开始 save_pretrained")
|
| 162 |
+
|
| 163 |
+
print(type(self.model_config), self.model_config)
|
| 164 |
+
for k, v in state_dict.items():
|
| 165 |
+
if isinstance(self.model_config, dict):
|
| 166 |
+
self.model.config[k] = v
|
| 167 |
+
else:
|
| 168 |
+
setattr(self.model_config, k, v)
|
| 169 |
+
t1 = time.perf_counter()
|
| 170 |
+
print(f"[{t1:.4f}] after setattr config (耗时 {t1 - t_start:.4f} 秒)")
|
| 171 |
+
|
| 172 |
+
if hasattr(self.model_config, "save_pretrained"):
|
| 173 |
+
self.model_config.save_pretrained(path)
|
| 174 |
+
else:
|
| 175 |
+
with open(os.path.join(path, "config.json"), "w") as f:
|
| 176 |
+
json.dump(self.model_config, f, indent=2)
|
| 177 |
+
if hasattr(self.model, "generation_config"):
|
| 178 |
+
print(type(self.model.generation_config), self.model.generation_config)
|
| 179 |
+
self.model.generation_config.save_pretrained(path)
|
| 180 |
+
# with open(os.path.join(path, "generation_config.json"), "w") as f:
|
| 181 |
+
# json.dump(self.model.generation_config, f, indent=2)
|
| 182 |
+
t2 = time.perf_counter()
|
| 183 |
+
print(f"[{t2:.4f}] self.model.save_config(path) (耗时 {t2 - t1:.4f} 秒)")
|
| 184 |
+
|
| 185 |
+
if self.weight_file_prefix != "":
|
| 186 |
+
self._save_pretrained_with_prefix(model_state_dict, path, self.weight_file_prefix)
|
| 187 |
+
else:
|
| 188 |
+
torch.save(model_state_dict, os.path.join(path, "pytorch_model.bin"))
|
| 189 |
+
t3 = time.perf_counter()
|
| 190 |
+
print(f"[{t3:.4f}] after save_pretrained (耗时 {t3 - t2:.4f} 秒)")
|
| 191 |
+
|
| 192 |
+
print(f"[{t3:.4f}] 总耗时 {t3 - t_start:.4f} 秒")
|
| 193 |
+
return model_state_dict
|
| 194 |
+
|
| 195 |
+
def _save_pretrained_with_prefix(self, state_dict, save_dir, weight_file_prefix):
|
| 196 |
+
suffix = "{suffix}"
|
| 197 |
+
pattern = f"{weight_file_prefix}{suffix}.safetensors"
|
| 198 |
+
save_torch_state_dict(
|
| 199 |
+
state_dict=state_dict,
|
| 200 |
+
save_directory=save_dir,
|
| 201 |
+
filename_pattern=pattern,
|
| 202 |
+
max_shard_size="5GB",
|
| 203 |
+
safe_serialization=True,
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
def get_decay(self, optimization_step: int) -> float:
|
| 207 |
+
"""
|
| 208 |
+
Compute the decay factor for the exponential moving average.
|
| 209 |
+
"""
|
| 210 |
+
step = max(0, optimization_step - self.update_after_step - 1)
|
| 211 |
+
|
| 212 |
+
if step <= 0:
|
| 213 |
+
return 0.0
|
| 214 |
+
|
| 215 |
+
if self.use_ema_warmup:
|
| 216 |
+
cur_decay_value = 1 - (1 + step / self.inv_gamma) ** -self.power
|
| 217 |
+
else:
|
| 218 |
+
cur_decay_value = (1 + step) / (10 + step)
|
| 219 |
+
|
| 220 |
+
cur_decay_value = min(cur_decay_value, self.decay)
|
| 221 |
+
# make sure decay is not smaller than min_decay
|
| 222 |
+
cur_decay_value = max(cur_decay_value, self.min_decay)
|
| 223 |
+
return cur_decay_value
|
| 224 |
+
|
| 225 |
+
@torch.no_grad()
|
| 226 |
+
def step(self, parameters: Iterable[torch.nn.Parameter]):
|
| 227 |
+
if isinstance(parameters, torch.nn.Module):
|
| 228 |
+
deprecation_message = (
|
| 229 |
+
"Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. "
|
| 230 |
+
"Please pass the parameters of the module instead."
|
| 231 |
+
)
|
| 232 |
+
deprecate(
|
| 233 |
+
"passing a `torch.nn.Module` to `ExponentialMovingAverage.step`",
|
| 234 |
+
"1.0.0",
|
| 235 |
+
deprecation_message,
|
| 236 |
+
standard_warn=False,
|
| 237 |
+
)
|
| 238 |
+
parameters = parameters.parameters()
|
| 239 |
+
|
| 240 |
+
parameters = list(parameters)
|
| 241 |
+
|
| 242 |
+
self.optimization_step += 1
|
| 243 |
+
|
| 244 |
+
# Compute the decay factor for the exponential moving average.
|
| 245 |
+
decay = self.get_decay(self.optimization_step)
|
| 246 |
+
self.cur_decay_value = decay
|
| 247 |
+
one_minus_decay = 1 - decay
|
| 248 |
+
# print(f'one_minus_decay {one_minus_decay}')
|
| 249 |
+
# https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/runtime/zero/partition_parameters.py#L1543
|
| 250 |
+
for s_param, param in zip(self.model.parameters(), parameters):
|
| 251 |
+
s_tensor, tensor = None, None
|
| 252 |
+
if hasattr(s_param, "ds_tensor"): # EMA ZeRO-3
|
| 253 |
+
# print('EMA ZeRO-3')
|
| 254 |
+
s_tensor = s_param.ds_tensor
|
| 255 |
+
if hasattr(param, "ds_tensor"): # DiT ZeRO-3
|
| 256 |
+
tensor = param.ds_tensor
|
| 257 |
+
else: # DiT ZeRO-2
|
| 258 |
+
rank, world_size = int(os.getenv("RANK")), int(os.getenv("WORLD_SIZE"))
|
| 259 |
+
partition_size = math.ceil(param.numel() / world_size)
|
| 260 |
+
start = partition_size * rank
|
| 261 |
+
end = start + partition_size
|
| 262 |
+
|
| 263 |
+
one_dim_param = param.data.contiguous().view(-1)
|
| 264 |
+
if start < param.numel() and end <= param.numel():
|
| 265 |
+
tensor = one_dim_param.narrow(0, start, partition_size)
|
| 266 |
+
elif start < param.numel():
|
| 267 |
+
# raise ValueError(f'start {start}, end {end}, param.numel() {param.numel()}, partition_size {partition_size}')
|
| 268 |
+
elems_to_copy = param.numel() - start
|
| 269 |
+
s_tensor = s_param.ds_tensor.narrow(0, 0, elems_to_copy)
|
| 270 |
+
tensor = one_dim_param.narrow(0, start, elems_to_copy)
|
| 271 |
+
else:
|
| 272 |
+
# raise ValueError(f'start {start}, end {end}, param.numel() {param.numel()}, partition_size {partition_size}')
|
| 273 |
+
continue
|
| 274 |
+
else: # DiT/EMA ZeRO-2
|
| 275 |
+
s_tensor = s_param.data
|
| 276 |
+
tensor = param.data
|
| 277 |
+
|
| 278 |
+
assert s_tensor.shape == tensor.shape, (
|
| 279 |
+
f"mismatch shape, s_tensor: {s_tensor.shape}, tensor: {tensor.shape}"
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
if param.requires_grad:
|
| 283 |
+
s_tensor.sub_(one_minus_decay * (s_tensor - tensor.to(s_tensor.dtype)))
|
| 284 |
+
else:
|
| 285 |
+
s_tensor.copy_(tensor)
|
| 286 |
+
|
| 287 |
+
def copy_to(self, parameters: Iterable[torch.nn.Parameter]) -> None:
|
| 288 |
+
"""
|
| 289 |
+
Copy current averaged parameters into given collection of parameters.
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
| 293 |
+
updated with the stored moving averages. If `None`, the parameters with which this
|
| 294 |
+
`ExponentialMovingAverage` was initialized will be used.
|
| 295 |
+
"""
|
| 296 |
+
parameters = list(parameters)
|
| 297 |
+
for s_param, param in zip(self.model.parameters(), parameters):
|
| 298 |
+
param.data.copy_(s_param.to(param.device).data)
|
| 299 |
+
|
| 300 |
+
def to(self, device=None, dtype=None) -> None:
|
| 301 |
+
r"""Move internal buffers of the ExponentialMovingAverage to `device`.
|
| 302 |
+
|
| 303 |
+
Args:
|
| 304 |
+
device: like `device` argument to `torch.Tensor.to`
|
| 305 |
+
"""
|
| 306 |
+
# .to() on the tensors handles None correctly
|
| 307 |
+
self.model = self.model.to(device=device, dtype=dtype)
|
| 308 |
+
|
| 309 |
+
def state_dict(self) -> dict:
|
| 310 |
+
r"""
|
| 311 |
+
Returns the state of the ExponentialMovingAverage as a dict. This method is used by accelerate during
|
| 312 |
+
checkpointing to save the ema state dict.
|
| 313 |
+
"""
|
| 314 |
+
# Following PyTorch conventions, references to tensors are returned:
|
| 315 |
+
# "returns a reference to the state and not its copy!" -
|
| 316 |
+
# https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict
|
| 317 |
+
return {
|
| 318 |
+
"decay": self.decay,
|
| 319 |
+
"min_decay": self.min_decay,
|
| 320 |
+
"optimization_step": self.optimization_step,
|
| 321 |
+
"update_after_step": self.update_after_step,
|
| 322 |
+
"use_ema_warmup": self.use_ema_warmup,
|
| 323 |
+
"inv_gamma": self.inv_gamma,
|
| 324 |
+
"power": self.power,
|
| 325 |
+
"weight_file_prefix": self.weight_file_prefix,
|
| 326 |
+
"model": self.model.state_dict(),
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
def store(self, parameters: Iterable[torch.nn.Parameter]) -> None:
|
| 330 |
+
r"""
|
| 331 |
+
Args:
|
| 332 |
+
Save the current parameters for restoring later.
|
| 333 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
| 334 |
+
temporarily stored.
|
| 335 |
+
"""
|
| 336 |
+
self.temp_stored_params = [param.detach().cpu().clone() for param in parameters]
|
| 337 |
+
|
| 338 |
+
def restore(self, parameters: Iterable[torch.nn.Parameter]) -> None:
|
| 339 |
+
r"""
|
| 340 |
+
Args:
|
| 341 |
+
Restore the parameters stored with the `store` method. Useful to validate the model with EMA parameters without:
|
| 342 |
+
affecting the original optimization process. Store the parameters before the `copy_to()` method. After
|
| 343 |
+
validation (or model saving), use this to restore the former parameters.
|
| 344 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
| 345 |
+
updated with the stored parameters. If `None`, the parameters with which this
|
| 346 |
+
`ExponentialMovingAverage` was initialized will be used.
|
| 347 |
+
"""
|
| 348 |
+
if self.temp_stored_params is None:
|
| 349 |
+
raise RuntimeError("This ExponentialMovingAverage has no `store()`ed weights to `restore()`")
|
| 350 |
+
for c_param, param in zip(self.temp_stored_params, parameters):
|
| 351 |
+
param.data.copy_(c_param.data)
|
| 352 |
+
|
| 353 |
+
# Better memory-wise.
|
| 354 |
+
self.temp_stored_params = None
|
| 355 |
+
|
| 356 |
+
def load_state_dict(self, state_dict: dict) -> None:
|
| 357 |
+
r"""
|
| 358 |
+
Args:
|
| 359 |
+
Loads the ExponentialMovingAverage state. This method is used by accelerate during checkpointing to save the
|
| 360 |
+
ema state dict.
|
| 361 |
+
state_dict (dict): EMA state. Should be an object returned
|
| 362 |
+
from a call to :meth:`state_dict`.
|
| 363 |
+
"""
|
| 364 |
+
# deepcopy, to be consistent with module API
|
| 365 |
+
state_dict = copy.deepcopy(state_dict)
|
| 366 |
+
|
| 367 |
+
self.decay = state_dict.get("decay", self.decay)
|
| 368 |
+
if self.decay < 0.0 or self.decay > 1.0:
|
| 369 |
+
raise ValueError("Decay must be between 0 and 1")
|
| 370 |
+
|
| 371 |
+
self.min_decay = state_dict.get("min_decay", self.min_decay)
|
| 372 |
+
if not isinstance(self.min_decay, float):
|
| 373 |
+
raise ValueError("Invalid min_decay")
|
| 374 |
+
|
| 375 |
+
self.optimization_step = state_dict.get("optimization_step", self.optimization_step)
|
| 376 |
+
if not isinstance(self.optimization_step, int):
|
| 377 |
+
raise ValueError("Invalid optimization_step")
|
| 378 |
+
|
| 379 |
+
self.update_after_step = state_dict.get("update_after_step", self.update_after_step)
|
| 380 |
+
if not isinstance(self.update_after_step, int):
|
| 381 |
+
raise ValueError("Invalid update_after_step")
|
| 382 |
+
|
| 383 |
+
self.use_ema_warmup = state_dict.get("use_ema_warmup", self.use_ema_warmup)
|
| 384 |
+
if not isinstance(self.use_ema_warmup, bool):
|
| 385 |
+
raise ValueError("Invalid use_ema_warmup")
|
| 386 |
+
|
| 387 |
+
self.inv_gamma = state_dict.get("inv_gamma", self.inv_gamma)
|
| 388 |
+
if not isinstance(self.inv_gamma, (float, int)):
|
| 389 |
+
raise ValueError("Invalid inv_gamma")
|
| 390 |
+
|
| 391 |
+
self.power = state_dict.get("power", self.power)
|
| 392 |
+
if not isinstance(self.power, (float, int)):
|
| 393 |
+
raise ValueError("Invalid power")
|
| 394 |
+
|
| 395 |
+
self.weight_file_prefix = state_dict.get("weight_file_prefix", self.weight_file_prefix)
|
| 396 |
+
if not isinstance(self.weight_file_prefix, (str)):
|
| 397 |
+
raise ValueError("Invalid weight_file_prefix")
|
| 398 |
+
|
| 399 |
+
model_state_dict = state_dict.get("model", None)
|
| 400 |
+
if model_state_dict is not None:
|
| 401 |
+
self.model.load_state_dict(model_state_dict)
|
Helios/_DEV/helios/utils/create_ema_zero3_lora.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import deepspeed
|
| 7 |
+
import torch
|
| 8 |
+
from peft import LoraConfig, set_peft_model_state_dict
|
| 9 |
+
from peft.utils import get_peft_model_state_dict
|
| 10 |
+
|
| 11 |
+
from diffusers.training_utils import _collate_lora_metadata, free_memory
|
| 12 |
+
from diffusers.utils import convert_unet_state_dict_to_peft
|
| 13 |
+
|
| 14 |
+
from ..pipelines.pipeline_helios import HeliosPipeline
|
| 15 |
+
from ..utils.create_ema_zero3 import EMAModel_Zero3, _z3_params_to_fetch
|
| 16 |
+
from ..utils.utils_base import NORM_LAYER_PREFIXES, load_extra_components, save_extra_components
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
GB = 1024 * 1024 * 1024
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Adapted from diffusers-style ema https://github.com/huggingface/diffusers/blob/main/src/diffusers/training_utils.py#L263
|
| 23 |
+
class EMAModel_Zero3_LoRA(EMAModel_Zero3):
|
| 24 |
+
"""
|
| 25 |
+
Exponential Moving Average of models weights
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
*args,
|
| 31 |
+
**kwargs,
|
| 32 |
+
):
|
| 33 |
+
super().__init__(*args, **kwargs)
|
| 34 |
+
|
| 35 |
+
@classmethod
|
| 36 |
+
def from_pretrained(
|
| 37 |
+
cls, args, path, model_cls, lora_config, transformer_additional_kwargs={}
|
| 38 |
+
) -> "EMAModel_Zero3_LoRA":
|
| 39 |
+
model = model_cls.from_pretrained(
|
| 40 |
+
args.model_config.transformer_model_name_or_path,
|
| 41 |
+
subfolder=args.model_config.subfolder or "transformer",
|
| 42 |
+
transformer_additional_kwargs=transformer_additional_kwargs,
|
| 43 |
+
)
|
| 44 |
+
model.add_adapter(lora_config)
|
| 45 |
+
|
| 46 |
+
# ------------- load lora -------------
|
| 47 |
+
lora_state_dict = HeliosPipeline.lora_state_dict(path)
|
| 48 |
+
model_state_dict = {
|
| 49 |
+
f"{k.replace('transformer.', '')}": v for k, v in lora_state_dict.items() if k.startswith("transformer.")
|
| 50 |
+
}
|
| 51 |
+
model_state_dict = convert_unet_state_dict_to_peft(model_state_dict)
|
| 52 |
+
incompatible_keys = set_peft_model_state_dict(model, model_state_dict, adapter_name="default")
|
| 53 |
+
if incompatible_keys is not None:
|
| 54 |
+
# check only for unexpected keys
|
| 55 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
| 56 |
+
if unexpected_keys:
|
| 57 |
+
accelerator.print(
|
| 58 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
| 59 |
+
f" {unexpected_keys}. "
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if args.model_config.train_norm_layers:
|
| 63 |
+
model_norm_state_dict = {
|
| 64 |
+
k: v
|
| 65 |
+
for k, v in lora_state_dict.items()
|
| 66 |
+
if k.startswith("transformer.") and any(norm_k in k for norm_k in NORM_LAYER_PREFIXES)
|
| 67 |
+
}
|
| 68 |
+
model._transformer_norm_layers = HeliosPipeline._load_norm_into_transformer(
|
| 69 |
+
model_norm_state_dict,
|
| 70 |
+
transformer=model,
|
| 71 |
+
discard_original_layers=False,
|
| 72 |
+
)
|
| 73 |
+
# ------------- load lora -------------
|
| 74 |
+
|
| 75 |
+
# ------------- load extra components -------------
|
| 76 |
+
load_extra_components(args, model, os.path.join(path, "transformer_partial.pth"))
|
| 77 |
+
# ------------- load extra components -------------
|
| 78 |
+
|
| 79 |
+
ema_model = cls(model, model_cls=model_cls, model_config=model.config)
|
| 80 |
+
|
| 81 |
+
with open(os.path.join(path, "ema_kwargs.json"), "r") as f:
|
| 82 |
+
ema_kwargs = json.load(f)
|
| 83 |
+
ema_model.load_state_dict(ema_kwargs)
|
| 84 |
+
|
| 85 |
+
return ema_model
|
| 86 |
+
|
| 87 |
+
def save_pretrained(
|
| 88 |
+
self, args, path, pretrained_name_or_path, lora_config, transformer_additional_kwargs={}, transformer_cpu=None
|
| 89 |
+
):
|
| 90 |
+
if self.model_cls is None:
|
| 91 |
+
raise ValueError("`save_pretrained` can only be used if `model_cls` was defined at __init__.")
|
| 92 |
+
|
| 93 |
+
if self.model_config is None:
|
| 94 |
+
raise ValueError("`save_pretrained` can only be used if `model_config` was defined at __init__.")
|
| 95 |
+
|
| 96 |
+
rank = int(os.getenv("RANK", "0"))
|
| 97 |
+
|
| 98 |
+
model_to_save = self.model.module if hasattr(self.model, "module") else self.model
|
| 99 |
+
model_state_dict = {}
|
| 100 |
+
for k, v in model_to_save.named_parameters():
|
| 101 |
+
# only gather z3 params
|
| 102 |
+
params_to_fetch = _z3_params_to_fetch([v])
|
| 103 |
+
with deepspeed.zero.GatheredParameters(params_to_fetch, enabled=len(params_to_fetch) > 0):
|
| 104 |
+
if rank == 0:
|
| 105 |
+
model_state_dict[k] = v.data.cpu().clone()
|
| 106 |
+
|
| 107 |
+
if rank == 0:
|
| 108 |
+
state_dict = self.state_dict()
|
| 109 |
+
state_dict.pop("model")
|
| 110 |
+
|
| 111 |
+
os.makedirs(path, exist_ok=True)
|
| 112 |
+
print(f"state_dict, {state_dict.keys()}")
|
| 113 |
+
t_start = time.perf_counter()
|
| 114 |
+
print(f"[{t_start:.4f}] self.model_cls.from_pretrained")
|
| 115 |
+
|
| 116 |
+
print("self.model_cls", self.model_cls)
|
| 117 |
+
if transformer_cpu is None:
|
| 118 |
+
model = self.model_cls.from_pretrained(
|
| 119 |
+
pretrained_name_or_path,
|
| 120 |
+
subfolder=args.model_config.subfolder or "transformer",
|
| 121 |
+
transformer_additional_kwargs=transformer_additional_kwargs,
|
| 122 |
+
)
|
| 123 |
+
model.add_adapter(lora_config)
|
| 124 |
+
else:
|
| 125 |
+
model = transformer_cpu
|
| 126 |
+
t1 = time.perf_counter()
|
| 127 |
+
print(f"[{t1:.4f}] after self.model_cls.from_pretrained (耗时 {t1 - t_start:.4f} 秒)")
|
| 128 |
+
|
| 129 |
+
miss, unexp = model.load_state_dict(model_state_dict, strict=False)
|
| 130 |
+
assert len(unexp) == 0, f"miss: {miss}; unexp: {unexp}"
|
| 131 |
+
|
| 132 |
+
# ------------- only save lora -------------
|
| 133 |
+
config_dict = model.config if hasattr(model, "config") else self.model_config
|
| 134 |
+
with open(os.path.join(path, "config.json"), "w") as f:
|
| 135 |
+
json.dump(config_dict, f, indent=2)
|
| 136 |
+
|
| 137 |
+
modules_to_save = {}
|
| 138 |
+
transformer_lora_layers_to_save = get_peft_model_state_dict(model)
|
| 139 |
+
if args.model_config.train_norm_layers:
|
| 140 |
+
transformer_norm_layers_to_save = {
|
| 141 |
+
f"transformer.{name}": param
|
| 142 |
+
for name, param in model.named_parameters()
|
| 143 |
+
if any(k in name for k in NORM_LAYER_PREFIXES)
|
| 144 |
+
}
|
| 145 |
+
transformer_lora_layers_to_save = {
|
| 146 |
+
**transformer_lora_layers_to_save,
|
| 147 |
+
**transformer_norm_layers_to_save,
|
| 148 |
+
}
|
| 149 |
+
modules_to_save["transformer"] = model
|
| 150 |
+
HeliosPipeline.save_lora_weights(
|
| 151 |
+
path,
|
| 152 |
+
transformer_lora_layers=transformer_lora_layers_to_save,
|
| 153 |
+
**_collate_lora_metadata(modules_to_save),
|
| 154 |
+
)
|
| 155 |
+
# ------------- only save lora -------------
|
| 156 |
+
|
| 157 |
+
# ------------- only save extra components -------------
|
| 158 |
+
save_extra_components(args, model_state_dict=model_state_dict, output_dir=path)
|
| 159 |
+
# ------------- only save extra components -------------
|
| 160 |
+
|
| 161 |
+
t2 = time.perf_counter()
|
| 162 |
+
print(f"[{t2:.4f}] after save_pretrained (耗时 {t2 - t1:.4f} 秒)")
|
| 163 |
+
|
| 164 |
+
print(f"[{t2:.4f}] 总耗时 {t2 - t_start:.4f} 秒")
|
| 165 |
+
|
| 166 |
+
with open(os.path.join(path, "ema_kwargs.json"), "w") as f:
|
| 167 |
+
json.dump(state_dict, f, indent=2)
|
| 168 |
+
|
| 169 |
+
model = None
|
| 170 |
+
transformer_cpu = None
|
| 171 |
+
params_to_fetch = None
|
| 172 |
+
state_dict = None
|
| 173 |
+
model_state_dict = None
|
| 174 |
+
transformer_lora_layers_to_save = None
|
| 175 |
+
transformer_norm_layers_to_save = None
|
| 176 |
+
modules_to_save = None
|
| 177 |
+
del model
|
| 178 |
+
del transformer_cpu
|
| 179 |
+
del params_to_fetch
|
| 180 |
+
del state_dict
|
| 181 |
+
del model_state_dict
|
| 182 |
+
del transformer_lora_layers_to_save
|
| 183 |
+
del transformer_norm_layers_to_save
|
| 184 |
+
del modules_to_save
|
| 185 |
+
free_memory()
|
| 186 |
+
|
| 187 |
+
print(f"rank {rank} done saved ema!")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def gather_zero3ema(accelerator, ema_model):
|
| 191 |
+
model_to_save = ema_model.model.module if hasattr(ema_model.model, "module") else ema_model.model
|
| 192 |
+
model_state_dict = {}
|
| 193 |
+
for k, v in model_to_save.named_parameters():
|
| 194 |
+
# only gather z3 params
|
| 195 |
+
params_to_fetch = _z3_params_to_fetch([v])
|
| 196 |
+
with deepspeed.zero.GatheredParameters(params_to_fetch, enabled=len(params_to_fetch) > 0):
|
| 197 |
+
# if accelerator.process_index == 0:
|
| 198 |
+
model_state_dict[k] = v.data.cpu().clone()
|
| 199 |
+
return model_state_dict
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def create_ema_model(
|
| 203 |
+
accelerator,
|
| 204 |
+
args,
|
| 205 |
+
transformer,
|
| 206 |
+
resume_checkpoint_path,
|
| 207 |
+
model_cls,
|
| 208 |
+
model_config,
|
| 209 |
+
ds_config=None,
|
| 210 |
+
lora_config=None,
|
| 211 |
+
update_after_step=0,
|
| 212 |
+
transformer_additional_kwargs={},
|
| 213 |
+
):
|
| 214 |
+
ds_config["train_micro_batch_size_per_gpu"] = args.training_config.train_batch_size
|
| 215 |
+
ds_config["fp16"]["enabled"] = False
|
| 216 |
+
ds_config["bf16"]["enabled"] = False
|
| 217 |
+
ds_config["gradient_accumulation_steps"] = args.training_config.gradient_accumulation_steps
|
| 218 |
+
ds_config["train_batch_size"] = (
|
| 219 |
+
args.training_config.train_batch_size
|
| 220 |
+
* args.training_config.gradient_accumulation_steps
|
| 221 |
+
* accelerator.num_processes
|
| 222 |
+
)
|
| 223 |
+
accelerator.print(f"EMA deepspeed config {ds_config}")
|
| 224 |
+
|
| 225 |
+
if resume_checkpoint_path:
|
| 226 |
+
ema_model = EMAModel_Zero3_LoRA.from_pretrained(
|
| 227 |
+
args=args,
|
| 228 |
+
path=resume_checkpoint_path,
|
| 229 |
+
model_cls=model_cls,
|
| 230 |
+
lora_config=lora_config,
|
| 231 |
+
transformer_additional_kwargs=transformer_additional_kwargs,
|
| 232 |
+
)
|
| 233 |
+
accelerator.print(f"Successully resume EMAModel_Zero3 from {resume_checkpoint_path}")
|
| 234 |
+
else:
|
| 235 |
+
ema_model = EMAModel_Zero3_LoRA(
|
| 236 |
+
copy.deepcopy(transformer),
|
| 237 |
+
decay=args.training_config.ema_decay,
|
| 238 |
+
model_cls=model_cls,
|
| 239 |
+
model_config=model_config,
|
| 240 |
+
update_after_step=update_after_step,
|
| 241 |
+
)
|
| 242 |
+
accelerator.print(f"EMAModel_Zero3 finish, memory_allocated: {torch.cuda.memory_allocated() / GB:.2f} GB")
|
| 243 |
+
accelerator.print("Successully deepcopy EMAModel_Zero3 from model")
|
| 244 |
+
ema_model.model, _, _, _ = deepspeed.initialize(
|
| 245 |
+
model=ema_model.model, config_params=ds_config, distributed_port=args.training_config.ema_zero3_port
|
| 246 |
+
)
|
| 247 |
+
return ema_model
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def create_ema_final(
|
| 251 |
+
accelerator,
|
| 252 |
+
args,
|
| 253 |
+
transformer_cpu,
|
| 254 |
+
model_cls,
|
| 255 |
+
ds_config,
|
| 256 |
+
transformer_lora_config,
|
| 257 |
+
update_after_step=0,
|
| 258 |
+
resume_checkpoint_path=None,
|
| 259 |
+
transformer_additional_kwargs=None,
|
| 260 |
+
):
|
| 261 |
+
ema_transformer = create_ema_model(
|
| 262 |
+
accelerator,
|
| 263 |
+
args=args,
|
| 264 |
+
transformer=transformer_cpu,
|
| 265 |
+
resume_checkpoint_path=resume_checkpoint_path,
|
| 266 |
+
model_cls=model_cls,
|
| 267 |
+
model_config=transformer_cpu.config,
|
| 268 |
+
ds_config=ds_config,
|
| 269 |
+
lora_config=transformer_lora_config,
|
| 270 |
+
update_after_step=update_after_step,
|
| 271 |
+
transformer_additional_kwargs=transformer_additional_kwargs,
|
| 272 |
+
)
|
| 273 |
+
free_memory()
|
| 274 |
+
return ema_transformer
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
if __name__ == "__main__":
|
| 278 |
+
import json
|
| 279 |
+
import sys
|
| 280 |
+
from argparse import Namespace
|
| 281 |
+
|
| 282 |
+
import deepspeed
|
| 283 |
+
from accelerate import Accelerator
|
| 284 |
+
|
| 285 |
+
sys.path.append("../../")
|
| 286 |
+
from helios.modules.transformer_helios import HeliosTransformer3DModel
|
| 287 |
+
|
| 288 |
+
args = Namespace()
|
| 289 |
+
args.data_config = Namespace()
|
| 290 |
+
args.training_config = Namespace()
|
| 291 |
+
args.model_config = Namespace()
|
| 292 |
+
args.training_config.train_batch_size = 1
|
| 293 |
+
args.training_config.gradient_accumulation_steps = 1
|
| 294 |
+
args.training_config.ema_decay = 0.999
|
| 295 |
+
args.training_config.ema_zero3_port = 10543
|
| 296 |
+
args.model_config.train_norm_layers = False
|
| 297 |
+
args.model_config.transformer_model_name_or_path = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
|
| 298 |
+
args.training_config.ema_deepspeed_config_file = "../../scripts/accelerate_configs/zero3.json"
|
| 299 |
+
resume_checkpoint_path = None
|
| 300 |
+
|
| 301 |
+
output_dir = "temp"
|
| 302 |
+
accelerator = Accelerator()
|
| 303 |
+
|
| 304 |
+
model_cls = HeliosTransformer3DModel
|
| 305 |
+
transformer = model_cls.from_pretrained(
|
| 306 |
+
args.model_config.transformer_model_name_or_path, subfolder="transformer", torch_dtype=torch.bfloat16
|
| 307 |
+
)
|
| 308 |
+
target_modules = set()
|
| 309 |
+
for name, module in transformer.named_modules():
|
| 310 |
+
if isinstance(module, torch.nn.Linear):
|
| 311 |
+
target_modules.add(name)
|
| 312 |
+
target_modules = list(target_modules)
|
| 313 |
+
lora_config = LoraConfig(
|
| 314 |
+
r=256,
|
| 315 |
+
lora_alpha=256,
|
| 316 |
+
# target_modules=["to_k", "to_v", "to_q", "to_out.0"],
|
| 317 |
+
target_modules=target_modules,
|
| 318 |
+
lora_dropout=0.0,
|
| 319 |
+
)
|
| 320 |
+
transformer.add_adapter(lora_config)
|
| 321 |
+
|
| 322 |
+
transformer_cpu = copy.deepcopy(transformer)
|
| 323 |
+
transformer.to(device=accelerator.device, dtype=torch.bfloat16)
|
| 324 |
+
accelerator.print(f"Load model finish, memory_allocated: {torch.cuda.memory_allocated() / GB:.2f} GB")
|
| 325 |
+
|
| 326 |
+
with open(args.training_config.ema_deepspeed_config_file, "r") as f:
|
| 327 |
+
ds_config = json.load(f)
|
| 328 |
+
|
| 329 |
+
ema_transformer = create_ema_final(
|
| 330 |
+
accelerator=accelerator,
|
| 331 |
+
args=args,
|
| 332 |
+
transformer_cpu=transformer_cpu,
|
| 333 |
+
model_cls=model_cls,
|
| 334 |
+
ds_config=ds_config,
|
| 335 |
+
transformer_lora_config=lora_config,
|
| 336 |
+
)
|
Helios/_DEV/tools/merge_lora_for_helios.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from argparse import Namespace
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
sys.path.append("../")
|
| 6 |
+
from helios.modules.transformer_helios import HeliosTransformer3DModel
|
| 7 |
+
from helios.pipelines.pipeline_helios import HeliosPipeline
|
| 8 |
+
from helios.utils.utils_base import load_extra_components
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
transformer_additional_kwargs = {
|
| 12 |
+
"has_multi_term_memory_patch": True,
|
| 13 |
+
"zero_history_timestep": True,
|
| 14 |
+
"guidance_cross_attn": True,
|
| 15 |
+
"restrict_self_attn": False,
|
| 16 |
+
"is_train_restrict_lora": False,
|
| 17 |
+
"restrict_lora": False,
|
| 18 |
+
"restrict_lora_rank": 128,
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
transformer = HeliosTransformer3DModel.from_pretrained(
|
| 22 |
+
"1_formal_ckpts/ablation_stage3_2_mid-train_v4_e2500-ema",
|
| 23 |
+
subfolder="transformer",
|
| 24 |
+
transformer_additional_kwargs=transformer_additional_kwargs,
|
| 25 |
+
)
|
| 26 |
+
pipe = HeliosPipeline.from_pretrained(
|
| 27 |
+
"Wan-AI/Wan2.1-T2V-14B-Diffusers",
|
| 28 |
+
transformer=transformer,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
pipe.load_lora_weights(
|
| 32 |
+
"ablation_stage3_3_post-train-emergency_only-gan/checkpoint-2000/model_ema/pytorch_lora_weights.safetensors",
|
| 33 |
+
adapter_name="default",
|
| 34 |
+
)
|
| 35 |
+
pipe.set_adapters(["default"], adapter_weights=[1.0])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
args = Namespace()
|
| 39 |
+
if not hasattr(args, "training_config"):
|
| 40 |
+
args.training_config = Namespace()
|
| 41 |
+
args.training_config.is_enable_stage1 = True
|
| 42 |
+
args.training_config.restrict_self_attn = True
|
| 43 |
+
args.training_config.is_amplify_history = True
|
| 44 |
+
args.training_config.is_use_gan = True
|
| 45 |
+
load_extra_components(
|
| 46 |
+
args,
|
| 47 |
+
transformer,
|
| 48 |
+
"ablation_stage3_3_post-train-emergency_only-gan/checkpoint-2000/model_ema/transformer_partial.pth",
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
pipe.fuse_lora()
|
| 52 |
+
pipe.unload_lora_weights()
|
| 53 |
+
pipe.transformer.save_pretrained(
|
| 54 |
+
"1_formal_ckpts/ablation_stage3_3_post-train-emergency_only-gan_e2000-ema/transformer"
|
| 55 |
+
)
|
Helios/_DEV/tools/merge_lora_for_wan.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from argparse import Namespace
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
sys.path.append("../")
|
| 6 |
+
from helios.modules.transformer_helios import HeliosTransformer3DModel
|
| 7 |
+
from helios.pipelines.pipeline_helios import HeliosPipeline
|
| 8 |
+
from helios.utils.utils_base import load_extra_components
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
transformer_additional_kwargs = {
|
| 12 |
+
"has_multi_term_memory_patch": False,
|
| 13 |
+
"zero_history_timestep": False,
|
| 14 |
+
"guidance_cross_attn": False,
|
| 15 |
+
"restrict_self_attn": False,
|
| 16 |
+
"is_train_restrict_lora": False,
|
| 17 |
+
"restrict_lora": False,
|
| 18 |
+
"restrict_lora_rank": 128,
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
transformer = HeliosTransformer3DModel.from_pretrained(
|
| 22 |
+
"Wan-AI/Wan2.1-T2V-14B-Diffusers",
|
| 23 |
+
subfolder="transformer",
|
| 24 |
+
transformer_additional_kwargs=transformer_additional_kwargs,
|
| 25 |
+
)
|
| 26 |
+
pipe = HeliosPipeline.from_pretrained(
|
| 27 |
+
"Wan-AI/Wan2.1-T2V-14B-Diffusers",
|
| 28 |
+
transformer=transformer,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
pipe.load_lora_weights(
|
| 32 |
+
"ablation_14B_single-res_length-21_t2v_rank128_bs128_new/checkpoint-1000/pytorch_lora_weights.safetensors",
|
| 33 |
+
adapter_name="default",
|
| 34 |
+
)
|
| 35 |
+
pipe.set_adapters(["default"], adapter_weights=[1.0])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
args = Namespace()
|
| 39 |
+
if not hasattr(args, "training_config"):
|
| 40 |
+
args.training_config = Namespace()
|
| 41 |
+
args.training_config.is_enable_stage1 = True
|
| 42 |
+
args.training_config.restrict_self_attn = True
|
| 43 |
+
args.training_config.is_amplify_history = True
|
| 44 |
+
args.training_config.is_use_gan = True
|
| 45 |
+
load_extra_components(
|
| 46 |
+
args,
|
| 47 |
+
transformer,
|
| 48 |
+
"ablation_14B_single-res_length-21_t2v_rank128_bs128_new/checkpoint-1000/transformer_partial.pth",
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
pipe.fuse_lora()
|
| 52 |
+
pipe.unload_lora_weights()
|
| 53 |
+
pipe.transformer.save_pretrained(
|
| 54 |
+
"1_formal_ckpts/ablation_14B_single-res_length-21_t2v_rank128_bs128_new_e1000/transformer"
|
| 55 |
+
)
|
Helios/_DEV/tools/remove_ckpt.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
DIR="./"
|
| 2 |
+
find "$DIR" -type d -name "pytorch_model" -exec rm -rf {} +
|
| 3 |
+
find "$DIR" -type d -name "distributed_checkpoint" -exec rm -rf {} +
|
| 4 |
+
find "$DIR" -type f -name "random_states_*" -exec rm -f {} +
|
| 5 |
+
find "$DIR" -type f -name "scheduler.bin*" -exec rm -f {} +
|
Helios/_DEV/tools/requirements_old.txt
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.7.1
|
| 2 |
+
torchvision==0.22.1
|
| 3 |
+
torchaudio==2.7.1
|
| 4 |
+
triton==3.3.1
|
| 5 |
+
# diffusers==0.36.0
|
| 6 |
+
# transformers==4.57.6
|
| 7 |
+
# sentence-transformers==5.2.3
|
| 8 |
+
# git+https://github.com/SHYuanBest/diffusers.git@test
|
| 9 |
+
# git+https://github.com/huggingface/transformers.git
|
| 10 |
+
# git+https://github.com/huggingface/sentence-transformers.git
|
| 11 |
+
transformers==4.57.6
|
| 12 |
+
tokenizers==0.22.0
|
| 13 |
+
sentence-transformers==2.2.2
|
| 14 |
+
accelerate==1.12.0
|
| 15 |
+
deepspeed==0.18.4
|
| 16 |
+
peft==0.17.1
|
| 17 |
+
hf-xet==1.1.5
|
| 18 |
+
huggingface-hub==0.36.0
|
| 19 |
+
zstandard==0.25.0
|
| 20 |
+
wandb==0.23.0
|
| 21 |
+
video-reader-rs==0.4.1
|
| 22 |
+
gradio==5.44.1
|
| 23 |
+
gradio_client==1.12.1
|
| 24 |
+
numpy<2.0.0
|
| 25 |
+
opencv-python
|
| 26 |
+
gradio
|
| 27 |
+
spaces
|
| 28 |
+
moviepy
|
| 29 |
+
imageio-ffmpeg
|
| 30 |
+
ftfy
|
| 31 |
+
Jinja2
|
| 32 |
+
einops
|
| 33 |
+
nvitop
|
| 34 |
+
packaging
|
| 35 |
+
ninja
|
| 36 |
+
omegaconf
|
| 37 |
+
mpi4py
|
| 38 |
+
hf-doc-builder
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
absl-py==2.4.0
|
| 2 |
+
accelerate==1.12.0
|
| 3 |
+
addict==2.4.0
|
| 4 |
+
aiofiles==22.1.0
|
| 5 |
+
aiohttp==3.8.4
|
| 6 |
+
aiosignal==1.3.1
|
| 7 |
+
aiosqlite==0.22.1
|
| 8 |
+
altair==5.5.0
|
| 9 |
+
annotated-doc==0.0.4
|
| 10 |
+
annotated-types==0.7.0
|
| 11 |
+
antlr4-python3-runtime==4.9.3
|
| 12 |
+
anyio==4.9.0
|
| 13 |
+
apex @ file:///apex
|
| 14 |
+
argon2-cffi==25.1.0
|
| 15 |
+
argon2-cffi-bindings==25.1.0
|
| 16 |
+
arrow==1.4.0
|
| 17 |
+
asn1crypto==1.5.1
|
| 18 |
+
asr-eval-tool @ file:///tmp/py_pkg.asr_eval_tool/dist/asr_eval_tool-1.0.0.125-py3-none-any.whl#sha256=505809aedcce9d18d6d69fe9b4590e3e8b1064bf0f13effcd58ce761a1e9128e
|
| 19 |
+
asttokens==3.0.0
|
| 20 |
+
astunparse==1.6.3
|
| 21 |
+
async-timeout==4.0.2
|
| 22 |
+
attrs==23.1.0
|
| 23 |
+
audioread==3.0.1
|
| 24 |
+
auraloss==0.4.0
|
| 25 |
+
azure-core==1.35.0
|
| 26 |
+
azure-identity==1.23.0
|
| 27 |
+
azure-storage-blob==12.25.1
|
| 28 |
+
azure-storage-file-datalake==12.20.0
|
| 29 |
+
babel==2.18.0
|
| 30 |
+
bcrypt==4.3.0
|
| 31 |
+
beautifulsoup4==4.13.4
|
| 32 |
+
bidict==0.23.1
|
| 33 |
+
bigvgan==2.4.1
|
| 34 |
+
bitsandbytes==0.47.0
|
| 35 |
+
black==26.1.0
|
| 36 |
+
bleach==6.3.0
|
| 37 |
+
blessed==1.21.0
|
| 38 |
+
blinker==1.9.0
|
| 39 |
+
blis==0.7.11
|
| 40 |
+
boto3==1.39.4
|
| 41 |
+
botocore==1.39.4
|
| 42 |
+
braceexpand==0.1.7
|
| 43 |
+
Brotli==1.1.0
|
| 44 |
+
bs4==0.0.1
|
| 45 |
+
bson==0.5.10
|
| 46 |
+
byted-bumi @ http://luban-source.byted.org/repository/scm/seed.speech.bumi_2.3.0.40.tar.gz#sha256=88970040e733c1f0fa408537939b6335bc556d85cecd755bd1ab7f7b80939f16
|
| 47 |
+
byted-dataloader==0.5.5
|
| 48 |
+
byted-encrypted-hdfs==0.5.5
|
| 49 |
+
byted-hdfs-io==0.3.16
|
| 50 |
+
byted-iceberg==0.2.257
|
| 51 |
+
byted-jarvis==1.0.27
|
| 52 |
+
byted-kms-encryption==0.0.6
|
| 53 |
+
byted-kmsv2inner==0.1.20
|
| 54 |
+
byted-lafka-internal==1.4.16rc1
|
| 55 |
+
byted-OmniDispatcher==1.0.0.37
|
| 56 |
+
byted-omnistore==1.0.1
|
| 57 |
+
byted-seed-models==1.1.3
|
| 58 |
+
byted-streaming==1.1.206
|
| 59 |
+
byted-unified-io==0.0.20
|
| 60 |
+
byted-wandb==0.13.93
|
| 61 |
+
byted_huggingface_hub==0.130.5
|
| 62 |
+
byted_remote_ikernel==0.4.8
|
| 63 |
+
bytedance-context==0.7.1
|
| 64 |
+
bytedance-metrics==0.5.2
|
| 65 |
+
bytedance.ckpt_io_metrics==0.0.27
|
| 66 |
+
bytedance.easycycle==1.1.37
|
| 67 |
+
bytedance.hdfs-stdenv==0.0.40
|
| 68 |
+
bytedance.modelhub==0.0.103
|
| 69 |
+
bytedance.ndtimeline==2.3.1
|
| 70 |
+
bytedance.servicediscovery==0.1.2
|
| 71 |
+
bytedbackgrounds==0.0.6
|
| 72 |
+
byteddatabus==1.0.6
|
| 73 |
+
byteddps==0.1.2
|
| 74 |
+
bytedenv==0.6.2
|
| 75 |
+
bytedeuler==0.42.1
|
| 76 |
+
bytedfeather==0.3.5
|
| 77 |
+
bytedidgenerator==1.0.5
|
| 78 |
+
bytedkafka==0.2.9
|
| 79 |
+
bytedkms==3.2.9
|
| 80 |
+
bytedkmsv2==0.10.59
|
| 81 |
+
bytedlogger==0.15.1
|
| 82 |
+
bytedlogid==0.2.1
|
| 83 |
+
bytedmemfd==0.2
|
| 84 |
+
bytedmetrics==0.9.0
|
| 85 |
+
bytedmoxing @ https://luban-source.byted.org/repository/scm/search.nlp.moxing_py_1.0.0.21.tar.gz#sha256=10a8d5ad88b1f12dcecd3350d1a7f414f6af966734a7b155c389baf5d5c1872b
|
| 86 |
+
bytedpymongo==2.0.5
|
| 87 |
+
bytedrh2==1.18.11
|
| 88 |
+
bytedservicediscovery==0.18.0
|
| 89 |
+
bytedsinfmetacenter==1.4.3
|
| 90 |
+
bytedtcc==1.4.4
|
| 91 |
+
bytedtitan @ http://luban-source.byted.org/repository/scm/data.aml.titan_1.0.0.151.tar.gz
|
| 92 |
+
bytedtos==1.1.16
|
| 93 |
+
bytedtrace==0.3.0
|
| 94 |
+
bytedzti==1.0.15
|
| 95 |
+
bytedztijwthelper==0.0.22
|
| 96 |
+
bytedztispiffe==0.0.16
|
| 97 |
+
cachetools==5.5.2
|
| 98 |
+
catalogue==2.0.10
|
| 99 |
+
certifi==2022.9.24
|
| 100 |
+
cffi==1.17.1
|
| 101 |
+
chardet==5.1.0
|
| 102 |
+
charset-normalizer==3.0.1
|
| 103 |
+
circuitbreaker==2.1.3
|
| 104 |
+
click==8.2.1
|
| 105 |
+
colorama==0.4.6
|
| 106 |
+
comm==0.2.3
|
| 107 |
+
confection==0.1.5
|
| 108 |
+
contourpy==1.0.7
|
| 109 |
+
cramjam==2.10.0
|
| 110 |
+
crcmod==1.7
|
| 111 |
+
cryptography==39.0.2
|
| 112 |
+
cxxfilt==0.3.0
|
| 113 |
+
cycler==0.11.0
|
| 114 |
+
cymem==2.0.11
|
| 115 |
+
Cython==3.1.2
|
| 116 |
+
dataclasses-json==0.6.7
|
| 117 |
+
datasets==4.0.0
|
| 118 |
+
dbus-python==1.3.2
|
| 119 |
+
debugpy==1.8.14
|
| 120 |
+
decorator==5.2.1
|
| 121 |
+
decord==0.6.0
|
| 122 |
+
deepspeed==0.18.4
|
| 123 |
+
defusedxml==0.7.1
|
| 124 |
+
Deprecated==1.2.18
|
| 125 |
+
-e git+https://github.com/huggingface/diffusers-new-model-addition-helios.git@50b565af2edd0574aa6678aec2d61268dd85b4a2#egg=diffusers
|
| 126 |
+
dill==0.3.8
|
| 127 |
+
distlib==0.3.9
|
| 128 |
+
distro==1.8.0
|
| 129 |
+
distro-info==1.5+deb12u1
|
| 130 |
+
dnspython==2.7.0
|
| 131 |
+
docker-pycreds==0.4.0
|
| 132 |
+
docstring_parser==0.16
|
| 133 |
+
ecdsa==0.19.1
|
| 134 |
+
editdistance==0.8.1
|
| 135 |
+
einops==0.6.0
|
| 136 |
+
emoji==2.14.0
|
| 137 |
+
entrypoints==0.4
|
| 138 |
+
et_xmlfile==2.0.0
|
| 139 |
+
executing==2.2.0
|
| 140 |
+
fairscale==0.4.13
|
| 141 |
+
fastapi==0.116.1
|
| 142 |
+
fastavro==1.11.1
|
| 143 |
+
fastjsonschema==2.21.2
|
| 144 |
+
ffmpy==0.6.0
|
| 145 |
+
filelock==3.18.0
|
| 146 |
+
flash-attn==2.5.8
|
| 147 |
+
flash-attn-3==3.0.0b1
|
| 148 |
+
Flask==2.3.3
|
| 149 |
+
flatbuffers==25.2.10
|
| 150 |
+
fonttools==4.38.0
|
| 151 |
+
fqdn==1.5.1
|
| 152 |
+
frozenlist==1.3.3
|
| 153 |
+
fsspec==2023.6.0
|
| 154 |
+
ftfy==6.1.1
|
| 155 |
+
func-timeout==4.3.5
|
| 156 |
+
fvcore==0.1.5.post20221221
|
| 157 |
+
gast==0.6.0
|
| 158 |
+
gensim==4.3.2
|
| 159 |
+
gevent==22.10.2
|
| 160 |
+
gitdb==4.0.12
|
| 161 |
+
GitPython==3.1.44
|
| 162 |
+
google-api-core==2.25.1
|
| 163 |
+
google-auth==2.40.3
|
| 164 |
+
google-auth-oauthlib==0.4.6
|
| 165 |
+
google-cloud-core==2.4.3
|
| 166 |
+
google-cloud-storage==2.10.0
|
| 167 |
+
google-crc32c==1.7.1
|
| 168 |
+
google-pasta==0.2.0
|
| 169 |
+
google-resumable-media==2.7.2
|
| 170 |
+
googleapis-common-protos==1.70.0
|
| 171 |
+
gpustat==1.1.1
|
| 172 |
+
GPUtil==1.4.0
|
| 173 |
+
gradio==6.8.0
|
| 174 |
+
gradio_client==2.2.0
|
| 175 |
+
greenlet==3.2.3
|
| 176 |
+
groovy==0.1.2
|
| 177 |
+
grpcio==1.73.1
|
| 178 |
+
gunicorn==20.1.0
|
| 179 |
+
h11==0.16.0
|
| 180 |
+
h5py==3.14.0
|
| 181 |
+
hf-doc-builder==0.5.0
|
| 182 |
+
hf-xet==1.3.2
|
| 183 |
+
hjson==3.1.0
|
| 184 |
+
httpcore==1.0.9
|
| 185 |
+
httplib2==0.20.4
|
| 186 |
+
httpx==0.28.1
|
| 187 |
+
huggingface_hub==1.4.1
|
| 188 |
+
idna==3.3
|
| 189 |
+
ImageIO==2.37.2
|
| 190 |
+
imageio-ffmpeg==0.6.0
|
| 191 |
+
imagesize==1.4.1
|
| 192 |
+
importlib-metadata==6.7.0
|
| 193 |
+
importlib-resources==5.12.0
|
| 194 |
+
iniconfig==2.1.0
|
| 195 |
+
iopath==0.1.10
|
| 196 |
+
iotop==0.6
|
| 197 |
+
ipaddress==1.0.23
|
| 198 |
+
ipdb==0.13.13
|
| 199 |
+
ipykernel==6.29.5
|
| 200 |
+
ipython==9.10.0
|
| 201 |
+
ipython-genutils==0.2.0
|
| 202 |
+
ipython_pygments_lexers==1.1.1
|
| 203 |
+
ipywidgets==8.1.8
|
| 204 |
+
isodate==0.7.2
|
| 205 |
+
isoduration==20.11.0
|
| 206 |
+
itsdangerous==2.2.0
|
| 207 |
+
jedi==0.19.2
|
| 208 |
+
Jinja2==3.1.3
|
| 209 |
+
jiter==0.10.0
|
| 210 |
+
jmespath==1.0.1
|
| 211 |
+
joblib==1.5.1
|
| 212 |
+
json5==0.13.0
|
| 213 |
+
jsonargparse==4.14.0
|
| 214 |
+
jsonpatch==1.33
|
| 215 |
+
jsonpath-ng==1.5.3
|
| 216 |
+
jsonpickle==3.0.4
|
| 217 |
+
jsonpointer==3.0.0
|
| 218 |
+
jsonschema==4.24.0
|
| 219 |
+
jsonschema-specifications==2025.4.1
|
| 220 |
+
jupyter==1.1.1
|
| 221 |
+
jupyter-client==7.0.0
|
| 222 |
+
jupyter-console==6.6.3
|
| 223 |
+
jupyter-events==0.12.0
|
| 224 |
+
jupyter-ydoc==0.2.5
|
| 225 |
+
jupyter_core==5.9.1
|
| 226 |
+
jupyter_server==2.17.0
|
| 227 |
+
jupyter_server_fileid==0.9.3
|
| 228 |
+
jupyter_server_terminals==0.5.4
|
| 229 |
+
jupyter_server_ydoc==0.8.0
|
| 230 |
+
jupyterlab==3.6.4
|
| 231 |
+
jupyterlab_pygments==0.3.0
|
| 232 |
+
jupyterlab_server==2.28.0
|
| 233 |
+
jupyterlab_widgets==3.0.16
|
| 234 |
+
keras==3.10.0
|
| 235 |
+
kernels==0.12.1
|
| 236 |
+
kiwisolver==1.4.4
|
| 237 |
+
langchain==0.1.19
|
| 238 |
+
langchain-community==0.0.38
|
| 239 |
+
langchain-core==0.1.53
|
| 240 |
+
langchain-text-splitters==0.0.2
|
| 241 |
+
langcodes==3.5.0
|
| 242 |
+
langsmith==0.1.147
|
| 243 |
+
language_data==1.3.0
|
| 244 |
+
lazr.restfulclient==0.14.5
|
| 245 |
+
lazr.uri==1.0.6
|
| 246 |
+
lazy_loader==0.4
|
| 247 |
+
libclang==18.1.1
|
| 248 |
+
librosa==0.11.0
|
| 249 |
+
liger_kernel==0.6.2
|
| 250 |
+
linkify-it-py==2.0.3
|
| 251 |
+
llvmlite==0.44.0
|
| 252 |
+
loguru==0.7.3
|
| 253 |
+
lpips==0.1.4
|
| 254 |
+
lxml==6.0.0
|
| 255 |
+
magi-attention @ file:///MagiAttention
|
| 256 |
+
marisa-trie==1.2.1
|
| 257 |
+
Markdown==3.8.2
|
| 258 |
+
markdown-it-py==2.2.0
|
| 259 |
+
MarkupSafe==2.1.5
|
| 260 |
+
marshmallow==3.26.1
|
| 261 |
+
matplotlib==3.7.0
|
| 262 |
+
matplotlib-inline==0.1.7
|
| 263 |
+
mdit-py-plugins==0.3.3
|
| 264 |
+
mdurl==0.1.2
|
| 265 |
+
miscreant==0.3.0
|
| 266 |
+
mistune==3.2.0
|
| 267 |
+
ml_dtypes==0.5.4
|
| 268 |
+
mmcv==2.0.0
|
| 269 |
+
mmengine==0.10.7
|
| 270 |
+
mmh3==4.1.0
|
| 271 |
+
mmhash3==3.0.1
|
| 272 |
+
mock==5.2.0
|
| 273 |
+
modelscope==1.34.0
|
| 274 |
+
moviepy==2.2.1
|
| 275 |
+
mpi4py==4.1.1
|
| 276 |
+
mpmath==1.3.0
|
| 277 |
+
msal==1.32.3
|
| 278 |
+
msal-extensions==1.3.1
|
| 279 |
+
msgpack==1.0.8
|
| 280 |
+
multidict==6.0.4
|
| 281 |
+
multiprocess==0.70.16
|
| 282 |
+
murmurhash==1.0.13
|
| 283 |
+
mypy_extensions==1.1.0
|
| 284 |
+
namex==0.1.0
|
| 285 |
+
narwhals==1.46.0
|
| 286 |
+
nbclassic==1.3.3
|
| 287 |
+
nbclient==0.10.4
|
| 288 |
+
nbconvert==7.17.0
|
| 289 |
+
nbformat==5.10.4
|
| 290 |
+
nest-asyncio==1.6.0
|
| 291 |
+
networkx==3.3
|
| 292 |
+
ninja==1.11.1.1
|
| 293 |
+
nlg-eval @ git+https://github.com/Maluuba/nlg-eval.git@2ab4528fad5548315cf61e40c2249fec8c8ad233
|
| 294 |
+
nltk==3.8.1
|
| 295 |
+
nnAudio==0.3.3
|
| 296 |
+
notebook==6.5.7
|
| 297 |
+
notebook_shim==0.2.4
|
| 298 |
+
numba==0.61.2
|
| 299 |
+
numpy==1.26.4
|
| 300 |
+
nvidia-cublas-cu12==12.8.3.14
|
| 301 |
+
nvidia-cuda-cupti-cu12==12.8.57
|
| 302 |
+
nvidia-cuda-nvrtc-cu12==12.8.61
|
| 303 |
+
nvidia-cuda-runtime-cu12==12.8.57
|
| 304 |
+
nvidia-cudnn-cu12==9.7.1.26
|
| 305 |
+
nvidia-cufft-cu12==11.3.3.41
|
| 306 |
+
nvidia-cufile-cu12==1.13.0.11
|
| 307 |
+
nvidia-curand-cu12==10.3.9.55
|
| 308 |
+
nvidia-cusolver-cu12==11.7.2.55
|
| 309 |
+
nvidia-cusparse-cu12==12.5.7.53
|
| 310 |
+
nvidia-cusparselt-cu12==0.6.3
|
| 311 |
+
nvidia-ml-py==13.580.65
|
| 312 |
+
nvidia-nccl-cu12==2.26.2
|
| 313 |
+
nvidia-nvjitlink-cu12==12.8.61
|
| 314 |
+
nvidia-nvtx-cu12==12.8.55
|
| 315 |
+
nvitop==1.6.2
|
| 316 |
+
oauthlib==3.2.2
|
| 317 |
+
oci==2.155.1
|
| 318 |
+
omegaconf==2.3.0
|
| 319 |
+
onnx==1.16.1
|
| 320 |
+
openai==1.105.0
|
| 321 |
+
opencv-python==4.7.0.72
|
| 322 |
+
openpyxl==3.1.2
|
| 323 |
+
opt_einsum==3.4.0
|
| 324 |
+
optree==0.16.0
|
| 325 |
+
orjson==3.10.18
|
| 326 |
+
overrides==7.7.0
|
| 327 |
+
packaging==24.2
|
| 328 |
+
pandas==2.3.1
|
| 329 |
+
pandocfilters==1.5.1
|
| 330 |
+
panther-gpu @ file:///torch/panther_gpu-1.7.14-cp311-cp311-linux_x86_64.whl#sha256=e00952ea8d43da2cfca9ed9c15d084d302d3fac4c2d5e2f9565c8d9b2ff9881f
|
| 331 |
+
paramiko==3.5.1
|
| 332 |
+
parso==0.8.4
|
| 333 |
+
pathlib2==2.3.7.post1
|
| 334 |
+
pathlib_abc==0.1.1
|
| 335 |
+
pathspec==1.0.4
|
| 336 |
+
pathtools==0.1.2
|
| 337 |
+
pathy==0.11.0
|
| 338 |
+
pdfminer.six==20231228
|
| 339 |
+
pdfplumber==0.11.4
|
| 340 |
+
peft==0.18.1
|
| 341 |
+
pesq==0.0.4
|
| 342 |
+
pexpect==4.8.0
|
| 343 |
+
pillow==11.3.0
|
| 344 |
+
pillow_heif==1.1.0
|
| 345 |
+
platformdirs==4.3.8
|
| 346 |
+
pluggy==1.6.0
|
| 347 |
+
ply==3.11
|
| 348 |
+
pooch==1.8.2
|
| 349 |
+
portalocker==3.2.0
|
| 350 |
+
preshed==3.0.10
|
| 351 |
+
prettytable==3.10.0
|
| 352 |
+
proglog==0.1.12
|
| 353 |
+
prometheus_client==0.24.1
|
| 354 |
+
promise==2.3
|
| 355 |
+
prompt_toolkit==3.0.51
|
| 356 |
+
propcache==0.3.2
|
| 357 |
+
proto-plus==1.26.1
|
| 358 |
+
protobuf==6.33.5
|
| 359 |
+
psutil==5.9.4
|
| 360 |
+
ptflops==0.7.4
|
| 361 |
+
ptyprocess==0.7.0
|
| 362 |
+
pure_eval==0.2.3
|
| 363 |
+
py==1.11.0
|
| 364 |
+
py-cpuinfo==9.0.0
|
| 365 |
+
py-spy==0.3.14
|
| 366 |
+
pyahocorasick==2.1.0
|
| 367 |
+
pyarrow==21.0.0
|
| 368 |
+
pyasn1==0.6.1
|
| 369 |
+
pyasn1_modules==0.4.2
|
| 370 |
+
pybind11==2.12.0
|
| 371 |
+
pycocoevalcap==1.2
|
| 372 |
+
pycocotools==2.0.6
|
| 373 |
+
pycparser==2.22
|
| 374 |
+
pycryptodomex==3.23.0
|
| 375 |
+
pydantic==2.11.7
|
| 376 |
+
pydantic_core==2.33.2
|
| 377 |
+
pydub==0.25.1
|
| 378 |
+
Pygments==2.19.2
|
| 379 |
+
PyGObject==3.42.2
|
| 380 |
+
PyJWT==2.10.1
|
| 381 |
+
PyNaCl==1.5.0
|
| 382 |
+
pynndescent==0.5.13
|
| 383 |
+
pyope==0.2.2
|
| 384 |
+
pyOpenSSL==23.2.0
|
| 385 |
+
pyparsing==3.0.9
|
| 386 |
+
pypdfium2==4.30.1
|
| 387 |
+
pyPEG2==2.15.2
|
| 388 |
+
pypinyin==0.48.0
|
| 389 |
+
pytest==6.2.5
|
| 390 |
+
python-apt==2.6.0
|
| 391 |
+
python-consul==1.1.0
|
| 392 |
+
python-dateutil==2.8.2
|
| 393 |
+
python-dotenv==1.2.1
|
| 394 |
+
python-engineio==4.12.2
|
| 395 |
+
python-etcd==0.4.5
|
| 396 |
+
python-jose==3.5.0
|
| 397 |
+
python-json-logger==4.0.0
|
| 398 |
+
python-multipart==0.0.20
|
| 399 |
+
python-snappy==0.7.3
|
| 400 |
+
python-socketio==5.13.0
|
| 401 |
+
pytokens==0.4.1
|
| 402 |
+
pytz==2025.2
|
| 403 |
+
pywsd==1.2.5
|
| 404 |
+
PyYAML==6.0
|
| 405 |
+
pyzmq==27.1.0
|
| 406 |
+
rapidfuzz==3.7.0
|
| 407 |
+
redis==4.5.5
|
| 408 |
+
referencing==0.36.2
|
| 409 |
+
regex==2022.10.31
|
| 410 |
+
requests==2.32.5
|
| 411 |
+
requests-oauthlib==2.0.0
|
| 412 |
+
requests-toolbelt==1.0.0
|
| 413 |
+
rfc3339-validator==0.1.4
|
| 414 |
+
rfc3986-validator==0.1.1
|
| 415 |
+
rich==13.9.4
|
| 416 |
+
rpds-py==0.26.0
|
| 417 |
+
rsa==4.9.1
|
| 418 |
+
ruff==0.12.11
|
| 419 |
+
s3transfer==0.13.0
|
| 420 |
+
sacrebleu==2.4.3
|
| 421 |
+
safehttpx==0.1.7
|
| 422 |
+
safetensors==0.5.3
|
| 423 |
+
schedule==1.2.2
|
| 424 |
+
scikit-learn==1.2.2
|
| 425 |
+
scipy==1.10.1
|
| 426 |
+
semantic-version==2.10.0
|
| 427 |
+
Send2Trash==2.1.0
|
| 428 |
+
sentence-transformers @ git+https://github.com/huggingface/sentence-transformers.git@58900864d51cde2f918885587709b2466938422c
|
| 429 |
+
sentencepiece==0.2.1
|
| 430 |
+
sentry-sdk==2.32.0
|
| 431 |
+
setproctitle==1.3.6
|
| 432 |
+
shapely==2.0.2
|
| 433 |
+
shellingham==1.5.4
|
| 434 |
+
shortuuid==1.0.13
|
| 435 |
+
shyaml==0.6.2
|
| 436 |
+
simple-websocket==1.1.0
|
| 437 |
+
six==1.16.0
|
| 438 |
+
smart-open==6.4.0
|
| 439 |
+
smmap==5.0.2
|
| 440 |
+
sniffio==1.3.1
|
| 441 |
+
sortedcontainers==2.4.0
|
| 442 |
+
soundfile==0.13.1
|
| 443 |
+
soupsieve==2.7
|
| 444 |
+
sox==1.5.0
|
| 445 |
+
soxbindings==1.2.3
|
| 446 |
+
soxr==0.5.0.post1
|
| 447 |
+
spaces==0.47.0
|
| 448 |
+
spacy==3.5.1
|
| 449 |
+
spacy-legacy==3.0.12
|
| 450 |
+
spacy-loggers==1.0.5
|
| 451 |
+
speech-evals @ file:///tmp/py_pkg.speech_evals/dist/speech_evals-1.0.0.34-py3-none-any.whl#sha256=521a1325b4d42fe67396f7d34b8daba0df225ba568a1cf35d517cd12d012f351
|
| 452 |
+
SQLAlchemy==2.0.41
|
| 453 |
+
srsly==2.5.1
|
| 454 |
+
stack-data==0.6.3
|
| 455 |
+
starlette==0.47.1
|
| 456 |
+
subword-nmt==0.3.8
|
| 457 |
+
sympy==1.13.3
|
| 458 |
+
tabulate==0.9.0
|
| 459 |
+
tbb==2022.2.0
|
| 460 |
+
tcmlib==1.4.0
|
| 461 |
+
tenacity==8.2.2
|
| 462 |
+
tensorboard==2.20.0
|
| 463 |
+
tensorboard-data-server==0.7.2
|
| 464 |
+
tensorboard-plugin-wit==1.8.1
|
| 465 |
+
tensorboardX==2.6.2.2
|
| 466 |
+
tensorflow==2.20.0
|
| 467 |
+
tensorflow-cpu==2.16.1
|
| 468 |
+
tensorflow-io==0.30.0
|
| 469 |
+
tensorflow-io-gcs-filesystem==0.30.0
|
| 470 |
+
termcolor==3.1.0
|
| 471 |
+
terminado==0.18.1
|
| 472 |
+
terminaltables==3.1.10
|
| 473 |
+
text-cutter @ https://luban-source.byted.org/repository/scm/search.nlp.libcut_py_2.3.0.52.tar.gz#sha256=c3689e2d0fa0323ef72a79eeb2adea7f3991513b87f6fa9ef0f8a66155737ce9
|
| 474 |
+
tf_keras==2.20.1
|
| 475 |
+
thinc==8.1.12
|
| 476 |
+
threadpoolctl==3.6.0
|
| 477 |
+
thrift2pyi==1.0.3
|
| 478 |
+
thriftpy2==0.5.2
|
| 479 |
+
timm==1.0.11
|
| 480 |
+
tinycss2==1.4.0
|
| 481 |
+
tokenizers==0.22.2
|
| 482 |
+
toml==0.10.2
|
| 483 |
+
tomlkit==0.13.3
|
| 484 |
+
torch==2.7.1+cu128
|
| 485 |
+
torchaudio==2.7.1+cu128
|
| 486 |
+
torchcodec==0.5
|
| 487 |
+
torchdata==0.11.0
|
| 488 |
+
torchlibrosa==0.1.0
|
| 489 |
+
torchvision==0.22.1+cu128
|
| 490 |
+
tornado==6.5.1
|
| 491 |
+
tox==3.28.0
|
| 492 |
+
tqdm==4.67.1
|
| 493 |
+
traitlets==5.14.3
|
| 494 |
+
transformers @ git+https://github.com/huggingface/transformers.git@11b1906d5c0dae39c13270e47cc02c4cde70e548
|
| 495 |
+
triton==3.3.1
|
| 496 |
+
typer==0.24.1
|
| 497 |
+
typer-slim==0.24.0
|
| 498 |
+
typing-inspect==0.9.0
|
| 499 |
+
typing-inspection==0.4.1
|
| 500 |
+
typing_extensions==4.12.2
|
| 501 |
+
tzdata==2025.2
|
| 502 |
+
uc-micro-py==1.0.3
|
| 503 |
+
umap-learn==0.5.4
|
| 504 |
+
unattended-upgrades==0.1
|
| 505 |
+
universal_pathlib==0.2.6
|
| 506 |
+
uri-template==1.3.0
|
| 507 |
+
urllib3==1.26.12
|
| 508 |
+
uvicorn==0.35.0
|
| 509 |
+
video_reader-rs==0.4.1
|
| 510 |
+
virtualenv==20.31.2
|
| 511 |
+
visdom==0.2.4
|
| 512 |
+
wadllib==1.3.6
|
| 513 |
+
wandb==0.23.0
|
| 514 |
+
wasabi==1.1.3
|
| 515 |
+
watchdog==6.0.0
|
| 516 |
+
wcwidth==0.2.13
|
| 517 |
+
webcolors==25.10.0
|
| 518 |
+
webdataset==0.2.48
|
| 519 |
+
webencodings==0.5.1
|
| 520 |
+
websocket-client==1.8.0
|
| 521 |
+
websockets==15.0.1
|
| 522 |
+
Werkzeug==3.1.3
|
| 523 |
+
widgetsnbextension==4.0.15
|
| 524 |
+
wn==0.0.23
|
| 525 |
+
word2number==1.1
|
| 526 |
+
wrapt==1.17.2
|
| 527 |
+
wsproto==1.2.0
|
| 528 |
+
xxhash==3.5.0
|
| 529 |
+
y-py==0.6.2
|
| 530 |
+
yacs==0.1.8
|
| 531 |
+
yapf==0.43.0
|
| 532 |
+
yarl==1.8.2
|
| 533 |
+
ypy-websocket==0.8.4
|
| 534 |
+
zhon==1.1.5
|
| 535 |
+
zipp==3.14.0
|
| 536 |
+
zope.event==5.1
|
| 537 |
+
zope.interface==7.2
|
| 538 |
+
zstandard==0.25.0
|
| 539 |
+
zstd==1.5.7.2
|
Helios/demo_data/MovieGenVideoBench_extended.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/demo_data/VBench_extended.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/eval/0_get_aesthetic.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import glob
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
import clip
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
from utils.utils import clip_transform, load_video
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
BATCH_SIZE = 32
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_aesthetic_model(path_to_model):
|
| 21 |
+
"""Load the aesthetic predictor model"""
|
| 22 |
+
m = nn.Linear(768, 1)
|
| 23 |
+
s = torch.load(path_to_model, map_location="cpu", weights_only=False)
|
| 24 |
+
m.load_state_dict(s)
|
| 25 |
+
m.eval()
|
| 26 |
+
return m
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def evaluate_aesthetic(aesthetic_model, clip_model, video_path, height=384, width=640, device="cuda"):
|
| 30 |
+
"""Evaluate aesthetic quality for a single video"""
|
| 31 |
+
aesthetic_model.eval()
|
| 32 |
+
clip_model.eval()
|
| 33 |
+
|
| 34 |
+
# Load video frames
|
| 35 |
+
images = load_video(video_path, height=height, width=width)
|
| 36 |
+
image_transform = clip_transform(224)
|
| 37 |
+
aesthetic_scores_list = []
|
| 38 |
+
|
| 39 |
+
# Process in batches
|
| 40 |
+
for i in range(0, len(images), BATCH_SIZE):
|
| 41 |
+
image_batch = images[i : i + BATCH_SIZE]
|
| 42 |
+
image_batch = image_transform(image_batch)
|
| 43 |
+
image_batch = image_batch.to(device)
|
| 44 |
+
|
| 45 |
+
with torch.no_grad():
|
| 46 |
+
image_feats = clip_model.encode_image(image_batch).to(torch.float32)
|
| 47 |
+
image_feats = F.normalize(image_feats, dim=-1, p=2)
|
| 48 |
+
aesthetic_scores = aesthetic_model(image_feats).squeeze(dim=-1)
|
| 49 |
+
|
| 50 |
+
aesthetic_scores_list.append(aesthetic_scores)
|
| 51 |
+
|
| 52 |
+
# Combine all scores
|
| 53 |
+
aesthetic_scores = torch.cat(aesthetic_scores_list, dim=0)
|
| 54 |
+
normalized_aesthetic_scores = aesthetic_scores / 10.0
|
| 55 |
+
avg_score = torch.mean(normalized_aesthetic_scores, dim=0, keepdim=True)
|
| 56 |
+
|
| 57 |
+
return avg_score.item()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def main(args):
|
| 61 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 62 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 63 |
+
output_json_path = os.path.join(output_path, "aesthetic_results.json")
|
| 64 |
+
|
| 65 |
+
# Set device
|
| 66 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 67 |
+
print(f"Using device: {device}")
|
| 68 |
+
|
| 69 |
+
# Load CSV file
|
| 70 |
+
if not os.path.exists(args.input_csv):
|
| 71 |
+
raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
|
| 72 |
+
|
| 73 |
+
df = pd.read_csv(args.input_csv)
|
| 74 |
+
df_dict = df.set_index("id").to_dict("index")
|
| 75 |
+
|
| 76 |
+
# Validate CSV columns
|
| 77 |
+
required_columns = ["id", "duration"]
|
| 78 |
+
for col in required_columns:
|
| 79 |
+
if col not in df.columns:
|
| 80 |
+
raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
|
| 81 |
+
|
| 82 |
+
# Load existing results if available
|
| 83 |
+
existing_results = {}
|
| 84 |
+
if os.path.exists(output_json_path):
|
| 85 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 86 |
+
with open(output_json_path, "r") as f:
|
| 87 |
+
existing_data = json.load(f)
|
| 88 |
+
for item in existing_data.get("per_video_results", []):
|
| 89 |
+
existing_results[item["id"]] = item
|
| 90 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 91 |
+
|
| 92 |
+
# Get all videos to process
|
| 93 |
+
video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
|
| 94 |
+
video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
|
| 95 |
+
print(f"\nFound {len(video_files)} videos in directory")
|
| 96 |
+
|
| 97 |
+
# Check which videos need processing
|
| 98 |
+
results = []
|
| 99 |
+
scores = []
|
| 100 |
+
videos_to_process = []
|
| 101 |
+
|
| 102 |
+
for video_path in video_files:
|
| 103 |
+
video_name = os.path.basename(video_path)
|
| 104 |
+
parts = video_name.replace(".mp4", "").split("_")
|
| 105 |
+
video_id = int(parts[0])
|
| 106 |
+
|
| 107 |
+
if video_id not in df_dict:
|
| 108 |
+
print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
# Check if already processed
|
| 112 |
+
if video_id in existing_results:
|
| 113 |
+
# Use existing result
|
| 114 |
+
results.append(existing_results[video_id])
|
| 115 |
+
scores.append(existing_results[video_id]["aesthetic_score"])
|
| 116 |
+
else:
|
| 117 |
+
# Need to process
|
| 118 |
+
videos_to_process.append((video_path, video_id, video_name))
|
| 119 |
+
|
| 120 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 121 |
+
print(f"Need to process: {len(videos_to_process)} videos")
|
| 122 |
+
|
| 123 |
+
# Process remaining videos
|
| 124 |
+
if videos_to_process:
|
| 125 |
+
# Load models
|
| 126 |
+
print("Loading CLIP model...")
|
| 127 |
+
clip_model, preprocess = clip.load(args.clip_model_path, device=device)
|
| 128 |
+
|
| 129 |
+
print("Loading aesthetic predictor model...")
|
| 130 |
+
aesthetic_model = get_aesthetic_model(args.aesthetic_model_path).to(device)
|
| 131 |
+
|
| 132 |
+
print("\nEvaluating remaining videos...")
|
| 133 |
+
for video_path, video_id, video_name in tqdm(videos_to_process):
|
| 134 |
+
try:
|
| 135 |
+
score = evaluate_aesthetic(
|
| 136 |
+
aesthetic_model,
|
| 137 |
+
clip_model,
|
| 138 |
+
video_path,
|
| 139 |
+
height=args.height,
|
| 140 |
+
width=args.width,
|
| 141 |
+
device=device,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
result_item = {"id": video_id, "video_name": video_name, "aesthetic_score": score}
|
| 145 |
+
results.append(result_item)
|
| 146 |
+
scores.append(score)
|
| 147 |
+
|
| 148 |
+
except Exception as e:
|
| 149 |
+
print(f"Error processing {video_name}: {str(e)}")
|
| 150 |
+
continue
|
| 151 |
+
else:
|
| 152 |
+
print("No videos to process. Skipping evaluation.")
|
| 153 |
+
return
|
| 154 |
+
|
| 155 |
+
# Calculate overall metrics
|
| 156 |
+
if scores:
|
| 157 |
+
avg_score = sum(scores) / len(scores)
|
| 158 |
+
|
| 159 |
+
# Sort results by video_id
|
| 160 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 161 |
+
|
| 162 |
+
output = {
|
| 163 |
+
"metric": "aesthetic",
|
| 164 |
+
"average_score": avg_score,
|
| 165 |
+
"num_videos": len(scores),
|
| 166 |
+
"per_video_results": results_sorted,
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
# Save results
|
| 170 |
+
os.makedirs(output_path, exist_ok=True)
|
| 171 |
+
with open(output_json_path, "w") as f:
|
| 172 |
+
json.dump(output, f, indent=2)
|
| 173 |
+
|
| 174 |
+
print(f"\n{'=' * 60}")
|
| 175 |
+
print("Results Summary:")
|
| 176 |
+
print(f"{'=' * 60}")
|
| 177 |
+
print(f"Average Aesthetic Score: {avg_score:.4f}")
|
| 178 |
+
print(f"Number of videos evaluated: {len(scores)}")
|
| 179 |
+
print(f"Results saved to: {output_json_path}")
|
| 180 |
+
print(f"{'=' * 60}\n")
|
| 181 |
+
else:
|
| 182 |
+
print("No videos were successfully evaluated!")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
parser = argparse.ArgumentParser(description="Evaluate video aesthetic using CLIP + LAION aesthetic predictor")
|
| 187 |
+
|
| 188 |
+
# Input/Output arguments
|
| 189 |
+
parser.add_argument("--height", type=str, default=384)
|
| 190 |
+
parser.add_argument("--width", type=str, default=640)
|
| 191 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 192 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 193 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 194 |
+
|
| 195 |
+
# Model arguments
|
| 196 |
+
parser.add_argument("--clip_model_path", type=str, default="checkpoints/aesthetic_model/ViT-L-14.pt")
|
| 197 |
+
parser.add_argument(
|
| 198 |
+
"--aesthetic_model_path", type=str, default="checkpoints/aesthetic_model/sa_0_4_vit_l_14_linear.pth"
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
args = parser.parse_args()
|
| 202 |
+
|
| 203 |
+
main(args)
|
Helios/eval/10_merge_all_results.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def collect_all_model_results(input_dir, score_type="normalized"):
|
| 8 |
+
model_results = {}
|
| 9 |
+
base_path = Path(input_dir)
|
| 10 |
+
|
| 11 |
+
for model_dir in base_path.iterdir():
|
| 12 |
+
if not model_dir.is_dir():
|
| 13 |
+
continue
|
| 14 |
+
|
| 15 |
+
merged_file = model_dir / "merged_results.json"
|
| 16 |
+
if not merged_file.exists():
|
| 17 |
+
print(f"⚠ Skipping {model_dir.name}: merged_results.json not found")
|
| 18 |
+
continue
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
with open(merged_file, "r") as f:
|
| 22 |
+
data = json.load(f)
|
| 23 |
+
|
| 24 |
+
model_name = model_dir.name
|
| 25 |
+
scores = {}
|
| 26 |
+
|
| 27 |
+
if score_type == "raw":
|
| 28 |
+
score_field = "raw_score"
|
| 29 |
+
elif score_type == "normalized":
|
| 30 |
+
score_field = "normalized_score"
|
| 31 |
+
elif score_type == "rating":
|
| 32 |
+
score_field = "rating"
|
| 33 |
+
else:
|
| 34 |
+
score_field = "normalized_score"
|
| 35 |
+
|
| 36 |
+
summary = data.get("summary", {})
|
| 37 |
+
|
| 38 |
+
for metric_key, metric_info in summary.get("non_drifting", {}).items():
|
| 39 |
+
scores[metric_key] = metric_info.get(score_field)
|
| 40 |
+
|
| 41 |
+
for metric_key, metric_info in summary.get("drifting", {}).items():
|
| 42 |
+
scores[metric_key] = metric_info.get(score_field)
|
| 43 |
+
|
| 44 |
+
if "total_weighted_rating" in summary:
|
| 45 |
+
scores["total_weighted_rating"] = summary["total_weighted_rating"]
|
| 46 |
+
|
| 47 |
+
model_results[model_name] = scores
|
| 48 |
+
print(f"✓ Loaded results for: {model_name}")
|
| 49 |
+
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"✗ Error loading {model_dir.name}/merged_results.json: {e}")
|
| 52 |
+
|
| 53 |
+
return model_results
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def create_final_merged_json(model_results, output_path, score_type="normalized", rating_scale=None):
|
| 57 |
+
all_metrics = set()
|
| 58 |
+
for scores in model_results.values():
|
| 59 |
+
all_metrics.update(scores.keys())
|
| 60 |
+
|
| 61 |
+
sorted_metrics = sorted([m for m in all_metrics if m != "total_weighted_rating"])
|
| 62 |
+
if "total_weighted_rating" in all_metrics:
|
| 63 |
+
sorted_metrics.append("total_weighted_rating")
|
| 64 |
+
|
| 65 |
+
final_data = {
|
| 66 |
+
"num_models": len(model_results),
|
| 67 |
+
"score_type": score_type,
|
| 68 |
+
"metrics": sorted_metrics,
|
| 69 |
+
"models": model_results,
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
if score_type == "rating" and rating_scale is not None:
|
| 73 |
+
final_data["rating_scale"] = rating_scale
|
| 74 |
+
|
| 75 |
+
with open(output_path, "w") as f:
|
| 76 |
+
json.dump(final_data, f, indent=2)
|
| 77 |
+
|
| 78 |
+
return final_data
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_rating_scale_from_results(input_dir):
|
| 82 |
+
base_path = Path(input_dir)
|
| 83 |
+
|
| 84 |
+
for model_dir in base_path.iterdir():
|
| 85 |
+
if not model_dir.is_dir():
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
merged_file = model_dir / "merged_results.json"
|
| 89 |
+
if merged_file.exists():
|
| 90 |
+
try:
|
| 91 |
+
with open(merged_file, "r") as f:
|
| 92 |
+
data = json.load(f)
|
| 93 |
+
rating_scale = data.get("rating_scale")
|
| 94 |
+
if rating_scale:
|
| 95 |
+
return rating_scale
|
| 96 |
+
except Exception:
|
| 97 |
+
continue
|
| 98 |
+
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def main(args):
|
| 103 |
+
input_dir = Path(args.input_dir)
|
| 104 |
+
|
| 105 |
+
if not input_dir.exists():
|
| 106 |
+
print(f"Error: Directory not found: {input_dir}")
|
| 107 |
+
return
|
| 108 |
+
|
| 109 |
+
score_type = args.score_type
|
| 110 |
+
|
| 111 |
+
rating_scale = None
|
| 112 |
+
if score_type == "rating":
|
| 113 |
+
rating_scale = get_rating_scale_from_results(input_dir)
|
| 114 |
+
if rating_scale:
|
| 115 |
+
score_type_str = f"RATING (1-{rating_scale})"
|
| 116 |
+
else:
|
| 117 |
+
score_type_str = "RATING"
|
| 118 |
+
elif score_type == "normalized":
|
| 119 |
+
score_type_str = "NORMALIZED"
|
| 120 |
+
elif score_type == "raw":
|
| 121 |
+
score_type_str = "RAW"
|
| 122 |
+
else:
|
| 123 |
+
score_type_str = score_type.upper()
|
| 124 |
+
|
| 125 |
+
print(f"\n{'=' * 100}")
|
| 126 |
+
print(f"ALL MODELS RESULTS MERGER (Using {score_type_str} Scores)")
|
| 127 |
+
print(f"{'=' * 100}")
|
| 128 |
+
print(f"Base Directory: {input_dir}\n")
|
| 129 |
+
|
| 130 |
+
model_results = collect_all_model_results(input_dir, score_type)
|
| 131 |
+
|
| 132 |
+
if not model_results:
|
| 133 |
+
print("\n✗ No model results found!")
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
print(f"\n✓ Successfully loaded {len(model_results)} models\n")
|
| 137 |
+
|
| 138 |
+
output_path = args.output_path or os.path.join(input_dir, "all_models_merged.json")
|
| 139 |
+
create_final_merged_json(model_results, output_path, score_type, rating_scale)
|
| 140 |
+
|
| 141 |
+
print(f"✓ All models merged results saved to: {output_path}\n")
|
| 142 |
+
|
| 143 |
+
return True
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
parser = argparse.ArgumentParser(description="Merge all models' merged_results.json into a single comparison file")
|
| 148 |
+
parser.add_argument("--input_dir", type=str, default="playground/results", help="Base directory")
|
| 149 |
+
parser.add_argument("--output_path", type=str, default=None)
|
| 150 |
+
parser.add_argument("--score_type", type=str, choices=["raw", "normalized", "rating"], default="rating")
|
| 151 |
+
args = parser.parse_args()
|
| 152 |
+
main(args)
|
Helios/eval/1_get_motion_amplitude.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import glob
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
from utils.utils import load_video
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _downscale_maps(flow_maps, downscale_size=16):
|
| 17 |
+
"""Resize flow maps for score calculation"""
|
| 18 |
+
downscaled = []
|
| 19 |
+
for flow in flow_maps:
|
| 20 |
+
h, w = flow.shape[:2]
|
| 21 |
+
new_h = int(h * (downscale_size / w))
|
| 22 |
+
downscaled.append(cv2.resize(flow, (downscale_size, new_h), interpolation=cv2.INTER_AREA))
|
| 23 |
+
return downscaled
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _motion_score(maps_or_masks):
|
| 27 |
+
"""Calculate mean score from maps or masks"""
|
| 28 |
+
if len(maps_or_masks) == 0:
|
| 29 |
+
return 0.0
|
| 30 |
+
average_map = np.mean(np.array(maps_or_masks), axis=0)
|
| 31 |
+
return float(np.mean(average_map))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def compute_farneback_optical_flow(frames):
|
| 35 |
+
"""Compute dense optical flow using Farneback algorithm"""
|
| 36 |
+
if len(frames) < 2:
|
| 37 |
+
return []
|
| 38 |
+
|
| 39 |
+
prev_gray = cv2.cvtColor(frames[0], cv2.COLOR_RGB2GRAY)
|
| 40 |
+
flow_maps = []
|
| 41 |
+
|
| 42 |
+
for frame in frames[1:]:
|
| 43 |
+
gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
|
| 44 |
+
flow_map = cv2.calcOpticalFlowFarneback(
|
| 45 |
+
prev_gray,
|
| 46 |
+
gray,
|
| 47 |
+
flow=None,
|
| 48 |
+
pyr_scale=0.5,
|
| 49 |
+
levels=3,
|
| 50 |
+
winsize=15,
|
| 51 |
+
iterations=3,
|
| 52 |
+
poly_n=5,
|
| 53 |
+
poly_sigma=1.2,
|
| 54 |
+
flags=0,
|
| 55 |
+
)
|
| 56 |
+
flow_maps.append(flow_map)
|
| 57 |
+
prev_gray = gray
|
| 58 |
+
|
| 59 |
+
return flow_maps
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def evaluate_motion(video_info, height=384, width=640):
|
| 63 |
+
video_path, video_id, video_name = video_info
|
| 64 |
+
try:
|
| 65 |
+
images = load_video(video_path, height=height, width=width, return_tensor=False)
|
| 66 |
+
farneback_maps = compute_farneback_optical_flow(images)
|
| 67 |
+
score = _motion_score(_downscale_maps(farneback_maps))
|
| 68 |
+
|
| 69 |
+
return {"id": video_id, "video_name": video_name, "motion_fb": abs(score), "success": True}
|
| 70 |
+
except Exception as e:
|
| 71 |
+
return {"id": video_id, "video_name": video_name, "error": str(e), "success": False}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def main(args):
|
| 75 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 76 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 77 |
+
output_json_path = os.path.join(output_path, "motion_amplitude_results.json")
|
| 78 |
+
|
| 79 |
+
# Load CSV file
|
| 80 |
+
if not os.path.exists(args.input_csv):
|
| 81 |
+
raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
|
| 82 |
+
|
| 83 |
+
df = pd.read_csv(args.input_csv)
|
| 84 |
+
df_dict = df.set_index("id").to_dict("index")
|
| 85 |
+
|
| 86 |
+
# Validate CSV columns
|
| 87 |
+
required_columns = ["id", "duration"]
|
| 88 |
+
for col in required_columns:
|
| 89 |
+
if col not in df.columns:
|
| 90 |
+
raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
|
| 91 |
+
|
| 92 |
+
# Load existing results if available
|
| 93 |
+
existing_results = {}
|
| 94 |
+
if os.path.exists(output_json_path):
|
| 95 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 96 |
+
with open(output_json_path, "r") as f:
|
| 97 |
+
existing_data = json.load(f)
|
| 98 |
+
for item in existing_data.get("per_video_results", []):
|
| 99 |
+
existing_results[item["id"]] = item
|
| 100 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 101 |
+
|
| 102 |
+
# Get all videos to process
|
| 103 |
+
video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
|
| 104 |
+
video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
|
| 105 |
+
print(f"\nFound {len(video_files)} videos in directory")
|
| 106 |
+
|
| 107 |
+
# Check which videos need processing
|
| 108 |
+
results = []
|
| 109 |
+
scores = []
|
| 110 |
+
videos_to_process = []
|
| 111 |
+
|
| 112 |
+
for video_path in video_files:
|
| 113 |
+
video_name = os.path.basename(video_path)
|
| 114 |
+
parts = video_name.replace(".mp4", "").split("_")
|
| 115 |
+
video_id = int(parts[0])
|
| 116 |
+
|
| 117 |
+
if video_id not in df_dict:
|
| 118 |
+
print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
|
| 119 |
+
continue
|
| 120 |
+
|
| 121 |
+
# Check if already processed
|
| 122 |
+
if video_id in existing_results:
|
| 123 |
+
# Use existing result
|
| 124 |
+
results.append(existing_results[video_id])
|
| 125 |
+
scores.append(existing_results[video_id]["motion_fb"])
|
| 126 |
+
else:
|
| 127 |
+
# Need to process
|
| 128 |
+
videos_to_process.append((video_path, video_id, video_name))
|
| 129 |
+
|
| 130 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 131 |
+
print(f"Need to process: {len(videos_to_process)} videos")
|
| 132 |
+
|
| 133 |
+
# Process remaining videos
|
| 134 |
+
if videos_to_process:
|
| 135 |
+
with ProcessPoolExecutor(max_workers=args.num_workers) as executor:
|
| 136 |
+
futures = [executor.submit(evaluate_motion, v, args.height, args.width) for v in videos_to_process]
|
| 137 |
+
|
| 138 |
+
for future in tqdm(as_completed(futures), total=len(futures), desc="Processing"):
|
| 139 |
+
res = future.result()
|
| 140 |
+
if res["success"]:
|
| 141 |
+
results.append({"id": res["id"], "video_name": res["video_name"], "motion_fb": res["motion_fb"]})
|
| 142 |
+
scores.append(res["motion_fb"])
|
| 143 |
+
else:
|
| 144 |
+
print(f"Error processing {res['video_name']}: {res.get('error')}")
|
| 145 |
+
else:
|
| 146 |
+
print("No videos to process. Skipping evaluation.")
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
# Calculate overall metrics
|
| 150 |
+
if scores:
|
| 151 |
+
avg_score = sum(scores) / len(scores)
|
| 152 |
+
|
| 153 |
+
# Sort results by video_id
|
| 154 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 155 |
+
|
| 156 |
+
output = {
|
| 157 |
+
"metric": "motion_fb",
|
| 158 |
+
"average_score": avg_score,
|
| 159 |
+
"num_videos": len(scores),
|
| 160 |
+
"per_video_results": results_sorted,
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
# Save results
|
| 164 |
+
os.makedirs(output_path, exist_ok=True)
|
| 165 |
+
with open(output_json_path, "w") as f:
|
| 166 |
+
json.dump(output, f, indent=2)
|
| 167 |
+
|
| 168 |
+
print(f"\n{'=' * 60}")
|
| 169 |
+
print("Results Summary:")
|
| 170 |
+
print(f"{'=' * 60}")
|
| 171 |
+
print(f"Average Motion Farneback Score: {avg_score:.4f}")
|
| 172 |
+
print(f"Number of videos evaluated: {len(scores)}")
|
| 173 |
+
print(f"Results saved to: {output_json_path}")
|
| 174 |
+
print(f"{'=' * 60}\n")
|
| 175 |
+
else:
|
| 176 |
+
print("No videos were successfully evaluated!")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
parser = argparse.ArgumentParser(description="Evaluate video motion farneback")
|
| 181 |
+
|
| 182 |
+
# Input/Output arguments
|
| 183 |
+
parser.add_argument("--height", type=int, default=384)
|
| 184 |
+
parser.add_argument("--width", type=int, default=640)
|
| 185 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 186 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 187 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 188 |
+
|
| 189 |
+
# Evaluation arguments
|
| 190 |
+
parser.add_argument("--num_workers", type=int, default=32)
|
| 191 |
+
|
| 192 |
+
args = parser.parse_args()
|
| 193 |
+
|
| 194 |
+
main(args)
|
Helios/eval/2_get_motion_smoothness.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import glob
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import torch
|
| 11 |
+
from omegaconf import OmegaConf
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
from utils.third_party.amt.utils.build_utils import build_from_cfg
|
| 15 |
+
from utils.third_party.amt.utils.utils import InputPadder, check_dim_and_resize, img2tensor, tensor2img
|
| 16 |
+
from utils.utils import align_dimension
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FrameProcess:
|
| 20 |
+
def __init__(self, height=384, width=640):
|
| 21 |
+
self.height = height
|
| 22 |
+
self.width = width
|
| 23 |
+
|
| 24 |
+
def get_frames(self, video_path):
|
| 25 |
+
"""Extract frames from MP4 video"""
|
| 26 |
+
frame_list = []
|
| 27 |
+
video = cv2.VideoCapture(video_path)
|
| 28 |
+
|
| 29 |
+
original_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 30 |
+
original_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 31 |
+
original_aspect_ratio = original_width / original_height
|
| 32 |
+
|
| 33 |
+
if self.width > self.height:
|
| 34 |
+
target_width = self.width
|
| 35 |
+
target_height = int(self.width / original_aspect_ratio)
|
| 36 |
+
else:
|
| 37 |
+
target_height = self.height
|
| 38 |
+
target_width = int(self.height * original_aspect_ratio)
|
| 39 |
+
|
| 40 |
+
target_height = align_dimension(target_height, 2)
|
| 41 |
+
target_width = align_dimension(target_width, 2)
|
| 42 |
+
|
| 43 |
+
while video.isOpened():
|
| 44 |
+
success, frame = video.read()
|
| 45 |
+
if success:
|
| 46 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 47 |
+
frame = cv2.resize(frame, (target_width, target_height))
|
| 48 |
+
frame_list.append(frame)
|
| 49 |
+
else:
|
| 50 |
+
break
|
| 51 |
+
video.release()
|
| 52 |
+
assert frame_list != [], "No frames extracted from video"
|
| 53 |
+
return frame_list
|
| 54 |
+
|
| 55 |
+
def extract_frame(self, frame_list, start_from=0):
|
| 56 |
+
extract = []
|
| 57 |
+
for i in range(start_from, len(frame_list), 2):
|
| 58 |
+
extract.append(frame_list[i])
|
| 59 |
+
return extract
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class MotionSmoothness:
|
| 63 |
+
def __init__(self, config, ckpt, height=384, width=640, device="cuda"):
|
| 64 |
+
self.device = device
|
| 65 |
+
self.config = config
|
| 66 |
+
self.ckpt = ckpt
|
| 67 |
+
self.niters = 1
|
| 68 |
+
self.height = height
|
| 69 |
+
self.width = width
|
| 70 |
+
self.initialization()
|
| 71 |
+
self.load_model()
|
| 72 |
+
|
| 73 |
+
def load_model(self):
|
| 74 |
+
"""Load AMT model"""
|
| 75 |
+
cfg_path = self.config
|
| 76 |
+
ckpt_path = self.ckpt
|
| 77 |
+
network_cfg = OmegaConf.load(cfg_path).network
|
| 78 |
+
network_name = network_cfg.name
|
| 79 |
+
print(f"Loading [{network_name}] from [{ckpt_path}]...")
|
| 80 |
+
|
| 81 |
+
self.model = build_from_cfg(network_cfg)
|
| 82 |
+
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 83 |
+
self.model.load_state_dict(ckpt["state_dict"])
|
| 84 |
+
self.model = self.model.to(self.device)
|
| 85 |
+
self.model.eval()
|
| 86 |
+
|
| 87 |
+
def initialization(self):
|
| 88 |
+
"""Initialize parameters based on device"""
|
| 89 |
+
if self.device.type == "cuda":
|
| 90 |
+
self.anchor_resolution = 1024 * 512
|
| 91 |
+
self.anchor_memory = 1500 * 1024**2
|
| 92 |
+
self.anchor_memory_bias = 2500 * 1024**2
|
| 93 |
+
self.vram_avail = torch.cuda.get_device_properties(self.device).total_memory
|
| 94 |
+
else:
|
| 95 |
+
self.anchor_resolution = 8192 * 8192
|
| 96 |
+
self.anchor_memory = 1
|
| 97 |
+
self.anchor_memory_bias = 0
|
| 98 |
+
self.vram_avail = 1
|
| 99 |
+
|
| 100 |
+
self.embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(self.device)
|
| 101 |
+
self.fp = FrameProcess(height=self.height, width=self.width)
|
| 102 |
+
|
| 103 |
+
def motion_score(self, video_path):
|
| 104 |
+
"""Calculate motion smoothness score for a video"""
|
| 105 |
+
iters = int(self.niters)
|
| 106 |
+
|
| 107 |
+
# Get frames
|
| 108 |
+
frames = self.fp.get_frames(video_path)
|
| 109 |
+
frame_list = self.fp.extract_frame(frames, start_from=0)
|
| 110 |
+
|
| 111 |
+
# Convert to tensors
|
| 112 |
+
inputs = [img2tensor(frame).to(self.device) for frame in frame_list]
|
| 113 |
+
assert len(inputs) > 1, f"Need more than one frame (current {len(inputs)})"
|
| 114 |
+
|
| 115 |
+
inputs = check_dim_and_resize(inputs)
|
| 116 |
+
h, w = inputs[0].shape[-2:]
|
| 117 |
+
scale = (
|
| 118 |
+
self.anchor_resolution
|
| 119 |
+
/ (h * w)
|
| 120 |
+
* np.sqrt((self.vram_avail - self.anchor_memory_bias) / self.anchor_memory)
|
| 121 |
+
)
|
| 122 |
+
scale = 1 if scale > 1 else scale
|
| 123 |
+
scale = 1 / np.floor(1 / np.sqrt(scale) * 16) * 16
|
| 124 |
+
|
| 125 |
+
if scale < 1:
|
| 126 |
+
print(f"Due to limited VRAM, video will be scaled by {scale:.2f}")
|
| 127 |
+
|
| 128 |
+
padding = int(16 / scale)
|
| 129 |
+
padder = InputPadder(inputs[0].shape, padding)
|
| 130 |
+
inputs = padder.pad(*inputs)
|
| 131 |
+
|
| 132 |
+
# Frame interpolation
|
| 133 |
+
for i in range(iters):
|
| 134 |
+
outputs = [inputs[0]]
|
| 135 |
+
for in_0, in_1 in zip(inputs[:-1], inputs[1:]):
|
| 136 |
+
in_0 = in_0.to(self.device)
|
| 137 |
+
in_1 = in_1.to(self.device)
|
| 138 |
+
with torch.no_grad():
|
| 139 |
+
imgt_pred = self.model(in_0, in_1, self.embt, scale_factor=scale, eval=True)["imgt_pred"]
|
| 140 |
+
outputs += [imgt_pred.cpu(), in_1.cpu()]
|
| 141 |
+
inputs = outputs
|
| 142 |
+
|
| 143 |
+
# Calculate VFI score
|
| 144 |
+
outputs = padder.unpad(*outputs)
|
| 145 |
+
outputs = [tensor2img(out) for out in outputs]
|
| 146 |
+
vfi_score = self.vfi_score(frames, outputs)
|
| 147 |
+
norm = (255.0 - vfi_score) / 255.0
|
| 148 |
+
|
| 149 |
+
return norm
|
| 150 |
+
|
| 151 |
+
def vfi_score(self, ori_frames, interpolate_frames):
|
| 152 |
+
"""Calculate video frame interpolation quality score"""
|
| 153 |
+
ori = self.fp.extract_frame(ori_frames, start_from=1)
|
| 154 |
+
interpolate = self.fp.extract_frame(interpolate_frames, start_from=1)
|
| 155 |
+
|
| 156 |
+
scores = []
|
| 157 |
+
for i in range(len(interpolate)):
|
| 158 |
+
scores.append(self.get_diff(ori[i], interpolate[i]))
|
| 159 |
+
|
| 160 |
+
return np.mean(np.array(scores))
|
| 161 |
+
|
| 162 |
+
def get_diff(self, img1, img2):
|
| 163 |
+
"""Calculate absolute difference between two images"""
|
| 164 |
+
img = cv2.absdiff(img1, img2)
|
| 165 |
+
return np.mean(img)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def main(args):
|
| 169 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 170 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 171 |
+
output_json_path = os.path.join(output_path, "motion_smoothness_results.json")
|
| 172 |
+
|
| 173 |
+
# Set device
|
| 174 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 175 |
+
print(f"Using device: {device}")
|
| 176 |
+
|
| 177 |
+
# Load CSV file
|
| 178 |
+
if not os.path.exists(args.input_csv):
|
| 179 |
+
raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
|
| 180 |
+
|
| 181 |
+
df = pd.read_csv(args.input_csv)
|
| 182 |
+
df_dict = df.set_index("id").to_dict("index")
|
| 183 |
+
|
| 184 |
+
# Validate CSV columns
|
| 185 |
+
required_columns = ["id", "duration"]
|
| 186 |
+
for col in required_columns:
|
| 187 |
+
if col not in df.columns:
|
| 188 |
+
raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
|
| 189 |
+
|
| 190 |
+
# Load existing results if available
|
| 191 |
+
existing_results = {}
|
| 192 |
+
if os.path.exists(output_json_path):
|
| 193 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 194 |
+
with open(output_json_path, "r") as f:
|
| 195 |
+
existing_data = json.load(f)
|
| 196 |
+
for item in existing_data.get("per_video_results", []):
|
| 197 |
+
existing_results[item["id"]] = item
|
| 198 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 199 |
+
|
| 200 |
+
# Get all videos to process
|
| 201 |
+
video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
|
| 202 |
+
video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
|
| 203 |
+
print(f"\nFound {len(video_files)} videos in directory")
|
| 204 |
+
|
| 205 |
+
# Check which videos need processing
|
| 206 |
+
results = []
|
| 207 |
+
scores = []
|
| 208 |
+
videos_to_process = []
|
| 209 |
+
|
| 210 |
+
for video_path in video_files:
|
| 211 |
+
video_name = os.path.basename(video_path)
|
| 212 |
+
parts = video_name.replace(".mp4", "").split("_")
|
| 213 |
+
video_id = int(parts[0])
|
| 214 |
+
|
| 215 |
+
if video_id not in df_dict:
|
| 216 |
+
print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
|
| 217 |
+
continue
|
| 218 |
+
|
| 219 |
+
# Check if already processed
|
| 220 |
+
if video_id in existing_results:
|
| 221 |
+
# Use existing result
|
| 222 |
+
results.append(existing_results[video_id])
|
| 223 |
+
scores.append(existing_results[video_id]["motion_smoothness_score"])
|
| 224 |
+
else:
|
| 225 |
+
# Need to process
|
| 226 |
+
videos_to_process.append((video_path, video_id, video_name))
|
| 227 |
+
|
| 228 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 229 |
+
print(f"Need to process: {len(videos_to_process)} videos")
|
| 230 |
+
|
| 231 |
+
# Process remaining videos
|
| 232 |
+
if videos_to_process:
|
| 233 |
+
# Load model
|
| 234 |
+
print("Loading AMT model...")
|
| 235 |
+
motion_evaluator = MotionSmoothness(
|
| 236 |
+
args.config, args.smoothness_model_path, height=args.height, width=args.width, device=device
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
print("\nEvaluating remaining videos...")
|
| 240 |
+
for video_path, video_id, video_name in tqdm(videos_to_process):
|
| 241 |
+
try:
|
| 242 |
+
score = motion_evaluator.motion_score(video_path)
|
| 243 |
+
|
| 244 |
+
result_item = {"id": video_id, "video_name": video_name, "motion_smoothness_score": float(score)}
|
| 245 |
+
results.append(result_item)
|
| 246 |
+
scores.append(float(score))
|
| 247 |
+
|
| 248 |
+
except Exception as e:
|
| 249 |
+
print(f"Error processing {video_name}: {str(e)}")
|
| 250 |
+
continue
|
| 251 |
+
else:
|
| 252 |
+
print("No videos to process. Skipping evaluation.")
|
| 253 |
+
return
|
| 254 |
+
|
| 255 |
+
# Calculate overall metrics
|
| 256 |
+
if scores:
|
| 257 |
+
avg_score = sum(scores) / len(scores)
|
| 258 |
+
|
| 259 |
+
# Sort results by video_id
|
| 260 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 261 |
+
|
| 262 |
+
output = {
|
| 263 |
+
"metric": "motion_smoothness",
|
| 264 |
+
"average_score": avg_score,
|
| 265 |
+
"num_videos": len(scores),
|
| 266 |
+
"per_video_results": results_sorted,
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
# Save results
|
| 270 |
+
os.makedirs(output_path, exist_ok=True)
|
| 271 |
+
with open(output_json_path, "w") as f:
|
| 272 |
+
json.dump(output, f, indent=2)
|
| 273 |
+
|
| 274 |
+
print(f"\n{'=' * 60}")
|
| 275 |
+
print("Results Summary:")
|
| 276 |
+
print(f"{'=' * 60}")
|
| 277 |
+
print(f"Average Motion Smoothness Score: {avg_score:.4f}")
|
| 278 |
+
print(f"Number of videos evaluated: {len(scores)}")
|
| 279 |
+
print(f"Results saved to: {output_json_path}")
|
| 280 |
+
print(f"{'=' * 60}\n")
|
| 281 |
+
else:
|
| 282 |
+
print("No videos were successfully evaluated!")
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
if __name__ == "__main__":
|
| 286 |
+
parser = argparse.ArgumentParser(description="Evaluate video motion smoothness using AMT model")
|
| 287 |
+
|
| 288 |
+
# Input/Output arguments
|
| 289 |
+
parser.add_argument("--height", type=str, default=384)
|
| 290 |
+
parser.add_argument("--width", type=str, default=640)
|
| 291 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 292 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 293 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 294 |
+
|
| 295 |
+
# Model arguments
|
| 296 |
+
parser.add_argument("--config", type=str, default="checkpoints/AMT-S.yaml")
|
| 297 |
+
parser.add_argument("--smoothness_model_path", type=str, default="checkpoints/amt_model/amt-s.pth")
|
| 298 |
+
|
| 299 |
+
args = parser.parse_args()
|
| 300 |
+
|
| 301 |
+
main(args)
|
Helios/eval/3_get_semantic.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import glob
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import torch
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
from utils.third_party.ViCLIP.simple_tokenizer import SimpleTokenizer
|
| 12 |
+
from utils.third_party.ViCLIP.viclip import ViCLIP
|
| 13 |
+
from utils.utils import clip_transform, read_frames_decord_by_fps
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_text_features(model, input_text, tokenizer, text_feature_dict={}):
|
| 17 |
+
"""Get text features from ViCLIP"""
|
| 18 |
+
if input_text in text_feature_dict:
|
| 19 |
+
return text_feature_dict[input_text]
|
| 20 |
+
|
| 21 |
+
text_template = f"{input_text}"
|
| 22 |
+
with torch.no_grad():
|
| 23 |
+
text_features = model.encode_text(text_template).float()
|
| 24 |
+
text_features /= text_features.norm(dim=-1, keepdim=True)
|
| 25 |
+
text_feature_dict[input_text] = text_features
|
| 26 |
+
|
| 27 |
+
return text_features
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_vid_features(model, input_frames):
|
| 31 |
+
"""Get video features from ViCLIP"""
|
| 32 |
+
with torch.no_grad():
|
| 33 |
+
clip_feat = model.encode_vision(input_frames, test=True).float()
|
| 34 |
+
clip_feat /= clip_feat.norm(dim=-1, keepdim=True)
|
| 35 |
+
return clip_feat
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def evaluate_overall_consistency(
|
| 39 |
+
viclip_model, tokenizer, video_path, prompt, height=384, width=640, device="cuda", sample_mode="middle"
|
| 40 |
+
):
|
| 41 |
+
"""Evaluate semantic consistency between video and prompt"""
|
| 42 |
+
image_transform = clip_transform(224)
|
| 43 |
+
|
| 44 |
+
with torch.no_grad():
|
| 45 |
+
# Load video frames
|
| 46 |
+
images = read_frames_decord_by_fps(video_path, height=height, width=width, num_frames=8, sample=sample_mode)
|
| 47 |
+
images = image_transform(images)
|
| 48 |
+
images = images.to(device)
|
| 49 |
+
|
| 50 |
+
# Get features
|
| 51 |
+
clip_feat = get_vid_features(viclip_model, images.unsqueeze(0))
|
| 52 |
+
text_feat = get_text_features(viclip_model, prompt, tokenizer)
|
| 53 |
+
|
| 54 |
+
# Calculate similarity
|
| 55 |
+
logit_per_text = clip_feat @ text_feat.T
|
| 56 |
+
score = float(logit_per_text[0][0].cpu())
|
| 57 |
+
|
| 58 |
+
return score
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def main(args):
|
| 62 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 63 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 64 |
+
output_json_path = os.path.join(output_path, "semantic_results.json")
|
| 65 |
+
|
| 66 |
+
# Set device
|
| 67 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 68 |
+
print(f"Using device: {device}")
|
| 69 |
+
|
| 70 |
+
# Load CSV file
|
| 71 |
+
if not os.path.exists(args.input_csv):
|
| 72 |
+
raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
|
| 73 |
+
|
| 74 |
+
df = pd.read_csv(args.input_csv)
|
| 75 |
+
df_dict = df.set_index("id").to_dict("index")
|
| 76 |
+
|
| 77 |
+
# Validate CSV columns
|
| 78 |
+
required_columns = ["id", "duration", "prompt"]
|
| 79 |
+
for col in required_columns:
|
| 80 |
+
if col not in df.columns:
|
| 81 |
+
raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
|
| 82 |
+
|
| 83 |
+
# Load existing results if available
|
| 84 |
+
existing_results = {}
|
| 85 |
+
if os.path.exists(output_json_path):
|
| 86 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 87 |
+
with open(output_json_path, "r") as f:
|
| 88 |
+
existing_data = json.load(f)
|
| 89 |
+
for item in existing_data.get("per_video_results", []):
|
| 90 |
+
existing_results[item["id"]] = item
|
| 91 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 92 |
+
|
| 93 |
+
# Get video files
|
| 94 |
+
video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
|
| 95 |
+
video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
|
| 96 |
+
print(f"\nFound {len(video_files)} videos in directory")
|
| 97 |
+
|
| 98 |
+
# Check which videos need processing
|
| 99 |
+
results = []
|
| 100 |
+
scores = []
|
| 101 |
+
videos_to_process = []
|
| 102 |
+
|
| 103 |
+
for video_path in video_files:
|
| 104 |
+
video_name = os.path.basename(video_path)
|
| 105 |
+
parts = video_name.replace(".mp4", "").split("_")
|
| 106 |
+
video_id = int(parts[0])
|
| 107 |
+
|
| 108 |
+
if video_id not in df_dict:
|
| 109 |
+
print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
# Check if already processed
|
| 113 |
+
if video_id in existing_results:
|
| 114 |
+
# Use existing result
|
| 115 |
+
results.append(existing_results[video_id])
|
| 116 |
+
scores.append(existing_results[video_id]["semantic_score"])
|
| 117 |
+
else:
|
| 118 |
+
# Need to process
|
| 119 |
+
prompt = df_dict[video_id]["prompt"]
|
| 120 |
+
videos_to_process.append((video_path, video_id, video_name, prompt))
|
| 121 |
+
|
| 122 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 123 |
+
print(f"Need to process: {len(videos_to_process)} videos")
|
| 124 |
+
|
| 125 |
+
# Process remaining videos
|
| 126 |
+
if videos_to_process:
|
| 127 |
+
# Load ViCLIP model
|
| 128 |
+
print("Loading ViCLIP model...")
|
| 129 |
+
tokenizer_path = os.path.join(args.semantic_model_path, "bpe_simple_vocab_16e6.txt.gz")
|
| 130 |
+
semantic_model_path = os.path.join(args.semantic_model_path, "ViClip-InternVid-10M-FLT.pth")
|
| 131 |
+
|
| 132 |
+
tokenizer = SimpleTokenizer(tokenizer_path)
|
| 133 |
+
viclip = ViCLIP(tokenizer=tokenizer, pretrain=semantic_model_path).to(device)
|
| 134 |
+
viclip.eval()
|
| 135 |
+
|
| 136 |
+
print("\nEvaluating remaining videos...")
|
| 137 |
+
for video_path, video_id, video_name, prompt in tqdm(videos_to_process):
|
| 138 |
+
try:
|
| 139 |
+
score = evaluate_overall_consistency(
|
| 140 |
+
viclip,
|
| 141 |
+
tokenizer,
|
| 142 |
+
video_path,
|
| 143 |
+
prompt,
|
| 144 |
+
height=args.height,
|
| 145 |
+
width=args.width,
|
| 146 |
+
sample_mode=args.sample_mode,
|
| 147 |
+
device=device,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
result_item = {"id": video_id, "video_name": video_name, "prompt": prompt, "semantic_score": score}
|
| 151 |
+
results.append(result_item)
|
| 152 |
+
scores.append(score)
|
| 153 |
+
|
| 154 |
+
except Exception as e:
|
| 155 |
+
print(f"Error processing {video_name}: {str(e)}")
|
| 156 |
+
continue
|
| 157 |
+
else:
|
| 158 |
+
print("No videos to process. Skipping evaluation.")
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
# Sort all results by video_id
|
| 162 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 163 |
+
|
| 164 |
+
# Calculate overall metrics and save final results
|
| 165 |
+
if scores:
|
| 166 |
+
avg_score = sum(scores) / len(scores)
|
| 167 |
+
|
| 168 |
+
output = {
|
| 169 |
+
"metric": "semantic",
|
| 170 |
+
"average_score": avg_score,
|
| 171 |
+
"num_videos": len(scores),
|
| 172 |
+
"per_video_results": results_sorted,
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
# Save results
|
| 176 |
+
os.makedirs(output_path, exist_ok=True)
|
| 177 |
+
with open(output_json_path, "w") as f:
|
| 178 |
+
json.dump(output, f, indent=2)
|
| 179 |
+
|
| 180 |
+
print(f"\n{'=' * 60}")
|
| 181 |
+
print("Results Summary:")
|
| 182 |
+
print(f"{'=' * 60}")
|
| 183 |
+
print(f"Average Semantic Score: {avg_score:.4f}")
|
| 184 |
+
print(f"Number of videos evaluated: {len(scores)}")
|
| 185 |
+
print(f"Results saved to: {output_json_path}")
|
| 186 |
+
print(f"{'=' * 60}\n")
|
| 187 |
+
else:
|
| 188 |
+
print("No videos were successfully evaluated!")
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
+
parser = argparse.ArgumentParser(description="Evaluate video semantic using ViCLIP model")
|
| 193 |
+
|
| 194 |
+
# Input/Output arguments
|
| 195 |
+
parser.add_argument("--height", type=str, default=384)
|
| 196 |
+
parser.add_argument("--width", type=str, default=640)
|
| 197 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 198 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 199 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 200 |
+
|
| 201 |
+
# Model arguments
|
| 202 |
+
parser.add_argument("--semantic_model_path", type=str, default="checkpoints/ViCLIP")
|
| 203 |
+
parser.add_argument("--sample_mode", type=str, default="middle", choices=["middle", "rand"])
|
| 204 |
+
|
| 205 |
+
args = parser.parse_args()
|
| 206 |
+
|
| 207 |
+
main(args)
|
Helios/eval/4_get_naturalness.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
|
| 9 |
+
import cv2
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from openai import OpenAI
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
PROMPT_VIDEO_DETECTION = """
|
| 16 |
+
Your task is to analyze ##NUM_FRAMES## frames sampled across a long video (e.g., ~1500 frames) to determine if it is AI-generated.
|
| 17 |
+
|
| 18 |
+
### CONTEXT:
|
| 19 |
+
Frames are sampled at wide intervals. Scene changes or camera movements are expected. Focus on individual frame integrity and local physical logic rather than global consistency.
|
| 20 |
+
|
| 21 |
+
### EVALUATION CRITERIA:
|
| 22 |
+
1. **Single-Frame Technical Flaws**: Look for AI-specific rendering "hallucinations":
|
| 23 |
+
- **Textures**: "Melting" surfaces, plastic-like skin, or chaotic patterns in complex areas (e.g., water ripples, foliage, fire).
|
| 24 |
+
- **Edges**: Unnatural blurring or "auras" around moving subjects where they meet the background.
|
| 25 |
+
2. **Local Physical Logic**: Within any given frame or small cluster of frames:
|
| 26 |
+
- Do shadows and reflections align with the visible light sources?
|
| 27 |
+
- Are objects interacting naturally with their environment (e.g., feet touching the ground properly, hands grasping objects correctly)?
|
| 28 |
+
3. **Biological Anomalies**: If humans appear, inspect for:
|
| 29 |
+
- Anatomical errors: Extra fingers, asymmetric eyes, or "fused" teeth.
|
| 30 |
+
- Unnatural micro-expressions or "dead" eyes lacking specular highlights.
|
| 31 |
+
4. **Transient Artifacts**: Even in sparse samples, look for "ghosting" or objects that seem to be partially transparent or merging with other objects (common in AI diffusion).
|
| 32 |
+
|
| 33 |
+
### SCORING SCALE:
|
| 34 |
+
- 1 (Definitely AI): Clear anatomical deformities, "melting" textures, or impossible physical interactions.
|
| 35 |
+
- 2 (Likely AI): Presence of "uncanny valley" effects, suspicious texture smoothing, or minor physical illogic.
|
| 36 |
+
- 3 (Uncertain): Ambiguous; could be low-quality real-world footage, heavy motion blur, or high-end AI.
|
| 37 |
+
- 4 (Likely Real): Consistent organic details, natural motion blur, and logical lighting.
|
| 38 |
+
- 5 (Definitely Real): Perfect high-frequency details (pores, fabric, grain), flawless physics, and natural anatomy.
|
| 39 |
+
|
| 40 |
+
### OUTPUT INSTRUCTION:
|
| 41 |
+
Return ONLY the integer score (1-5). No explanation.
|
| 42 |
+
""".strip()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def image_to_base64(image):
|
| 46 |
+
"""Convert image to base64 string"""
|
| 47 |
+
_, buffer = cv2.imencode(".jpg", image)
|
| 48 |
+
return base64.b64encode(buffer).decode("utf-8")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def resize_long_side(image, target_long=512):
|
| 52 |
+
"""Resize image keeping aspect ratio"""
|
| 53 |
+
h, w = image.shape[:2]
|
| 54 |
+
if h >= w:
|
| 55 |
+
new_h = target_long
|
| 56 |
+
new_w = int(w * target_long / h)
|
| 57 |
+
else:
|
| 58 |
+
new_w = target_long
|
| 59 |
+
new_h = int(h * target_long / w)
|
| 60 |
+
return cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def extract_frames(video_path, num_frames=16):
|
| 64 |
+
"""Extract frames from video"""
|
| 65 |
+
cap = cv2.VideoCapture(video_path)
|
| 66 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 67 |
+
frame_interval = max(total_frames // num_frames, 1)
|
| 68 |
+
frames = []
|
| 69 |
+
|
| 70 |
+
for i in range(num_frames):
|
| 71 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, i * frame_interval)
|
| 72 |
+
ret, frame = cap.read()
|
| 73 |
+
if ret:
|
| 74 |
+
resized = resize_long_side(frame, 512)
|
| 75 |
+
frames.append(resized)
|
| 76 |
+
|
| 77 |
+
cap.release()
|
| 78 |
+
return frames
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# @retry(wait=wait_exponential(min=2, max=10), stop=stop_after_attempt(5))
|
| 82 |
+
def call_gpt(image_frames_base64, model_name, api_key, base_url, num_frames=16, temperature=0.0):
|
| 83 |
+
"""Call GPT API to evaluate video naturalness"""
|
| 84 |
+
client = OpenAI(api_key=api_key, base_url=base_url)
|
| 85 |
+
|
| 86 |
+
content_list = []
|
| 87 |
+
for frame in image_frames_base64:
|
| 88 |
+
content_list.append(
|
| 89 |
+
{
|
| 90 |
+
"type": "image_url",
|
| 91 |
+
"image_url": {"url": f"data:image/jpeg;base64,{frame}"},
|
| 92 |
+
}
|
| 93 |
+
)
|
| 94 |
+
content_list.append({"type": "text", "text": PROMPT_VIDEO_DETECTION.replace("##NUM_FRAMES##", str(num_frames))})
|
| 95 |
+
|
| 96 |
+
response = client.chat.completions.create(
|
| 97 |
+
model=model_name,
|
| 98 |
+
stream=False,
|
| 99 |
+
temperature=temperature,
|
| 100 |
+
messages=[{"role": "user", "content": content_list}],
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
score = response.choices[0].message.content.strip()
|
| 104 |
+
return score
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def evaluate_naturalness(video_path, api_key, model_name, base_url, num_frames=16):
|
| 108 |
+
"""Evaluate naturalness for a single video"""
|
| 109 |
+
try:
|
| 110 |
+
frames = extract_frames(video_path, num_frames)
|
| 111 |
+
frames_base64 = [image_to_base64(f) for f in frames]
|
| 112 |
+
score_str = call_gpt(frames_base64, model_name, api_key, base_url, num_frames)
|
| 113 |
+
|
| 114 |
+
# Parse score (try to extract number from response)
|
| 115 |
+
score = float(score_str)
|
| 116 |
+
score = max(1.0, min(5.0, score))
|
| 117 |
+
# Normalize to [0, 1] if score is 1-5
|
| 118 |
+
score = (score - 1) / 4.0 # Convert 1-5 to 0-1
|
| 119 |
+
|
| 120 |
+
return score, score_str
|
| 121 |
+
except Exception as e:
|
| 122 |
+
print(f"Error evaluating video: {str(e)}")
|
| 123 |
+
raise
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def process_video_worker(args_tuple):
|
| 127 |
+
"""Worker function for parallel processing"""
|
| 128 |
+
video_path, video_id, video_name, api_key, model_name, base_url, num_frames = args_tuple
|
| 129 |
+
try:
|
| 130 |
+
score, raw_score = evaluate_naturalness(video_path, api_key, model_name, base_url, num_frames)
|
| 131 |
+
return {
|
| 132 |
+
"id": video_id,
|
| 133 |
+
"video_name": video_name,
|
| 134 |
+
"naturalness_score": score,
|
| 135 |
+
"raw_score": raw_score,
|
| 136 |
+
}
|
| 137 |
+
except Exception as e:
|
| 138 |
+
print(f"Error processing {video_name}: {str(e)}")
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def main(args):
|
| 143 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 144 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 145 |
+
output_json_path = os.path.join(output_path, "naturalness_results.json")
|
| 146 |
+
|
| 147 |
+
print(f"Using API: {args.base_url}")
|
| 148 |
+
print(f"Model: {args.model_name}")
|
| 149 |
+
|
| 150 |
+
# Load CSV file
|
| 151 |
+
if not os.path.exists(args.input_csv):
|
| 152 |
+
raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
|
| 153 |
+
|
| 154 |
+
df = pd.read_csv(args.input_csv)
|
| 155 |
+
df_dict = df.set_index("id").to_dict("index")
|
| 156 |
+
|
| 157 |
+
# Validate CSV columns
|
| 158 |
+
required_columns = ["id", "duration"]
|
| 159 |
+
for col in required_columns:
|
| 160 |
+
if col not in df.columns:
|
| 161 |
+
raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
|
| 162 |
+
|
| 163 |
+
# Load existing results if available
|
| 164 |
+
existing_results = {}
|
| 165 |
+
if os.path.exists(output_json_path):
|
| 166 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 167 |
+
with open(output_json_path, "r") as f:
|
| 168 |
+
existing_data = json.load(f)
|
| 169 |
+
for item in existing_data.get("per_video_results", []):
|
| 170 |
+
existing_results[item["id"]] = item
|
| 171 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 172 |
+
|
| 173 |
+
# Get video files
|
| 174 |
+
video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
|
| 175 |
+
video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
|
| 176 |
+
print(f"\nFound {len(video_files)} videos in directory")
|
| 177 |
+
|
| 178 |
+
# Check which videos need processing
|
| 179 |
+
results = []
|
| 180 |
+
tasks = []
|
| 181 |
+
|
| 182 |
+
for video_path in video_files:
|
| 183 |
+
video_name = os.path.basename(video_path)
|
| 184 |
+
parts = video_name.replace(".mp4", "").split("_")
|
| 185 |
+
video_id = int(parts[0])
|
| 186 |
+
|
| 187 |
+
if video_id not in df_dict:
|
| 188 |
+
print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
|
| 189 |
+
continue
|
| 190 |
+
|
| 191 |
+
# Check if already processed
|
| 192 |
+
if video_id in existing_results:
|
| 193 |
+
# Use existing result
|
| 194 |
+
results.append(existing_results[video_id])
|
| 195 |
+
else:
|
| 196 |
+
# Need to process
|
| 197 |
+
tasks.append(
|
| 198 |
+
(
|
| 199 |
+
video_path,
|
| 200 |
+
video_id,
|
| 201 |
+
video_name,
|
| 202 |
+
args.api_key,
|
| 203 |
+
args.model_name,
|
| 204 |
+
args.base_url,
|
| 205 |
+
args.num_frames,
|
| 206 |
+
)
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 210 |
+
print(f"Need to process: {len(tasks)} videos")
|
| 211 |
+
|
| 212 |
+
# Evaluate remaining videos in parallel
|
| 213 |
+
if tasks:
|
| 214 |
+
results_dict = {}
|
| 215 |
+
|
| 216 |
+
print(f"Evaluating videos with {args.num_workers} workers...")
|
| 217 |
+
|
| 218 |
+
with ThreadPoolExecutor(max_workers=args.num_workers) as executor:
|
| 219 |
+
future_to_idx = {executor.submit(process_video_worker, task): idx for idx, task in enumerate(tasks)}
|
| 220 |
+
|
| 221 |
+
for future in tqdm(as_completed(future_to_idx), total=len(tasks), desc="Evaluating"):
|
| 222 |
+
idx = future_to_idx[future]
|
| 223 |
+
result = future.result()
|
| 224 |
+
if result is not None:
|
| 225 |
+
results_dict[idx] = result
|
| 226 |
+
|
| 227 |
+
# Add new results in order
|
| 228 |
+
new_results = [results_dict[i] for i in sorted(results_dict.keys())]
|
| 229 |
+
results.extend(new_results)
|
| 230 |
+
else:
|
| 231 |
+
print("No videos to process. Skipping evaluation.")
|
| 232 |
+
return
|
| 233 |
+
|
| 234 |
+
# Sort all results by video_id
|
| 235 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 236 |
+
scores = [r["naturalness_score"] for r in results_sorted]
|
| 237 |
+
|
| 238 |
+
# Calculate overall metrics
|
| 239 |
+
if scores:
|
| 240 |
+
avg_score = sum(scores) / len(scores)
|
| 241 |
+
|
| 242 |
+
output = {
|
| 243 |
+
"metric": "naturalness",
|
| 244 |
+
"average_score": avg_score,
|
| 245 |
+
"num_videos": len(scores),
|
| 246 |
+
"model_name": args.model_name,
|
| 247 |
+
"num_frames_per_video": args.num_frames,
|
| 248 |
+
"per_video_results": results_sorted,
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
# Save results
|
| 252 |
+
os.makedirs(output_path, exist_ok=True)
|
| 253 |
+
|
| 254 |
+
with open(output_json_path, "w") as f:
|
| 255 |
+
json.dump(output, f, indent=2)
|
| 256 |
+
|
| 257 |
+
print(f"\n{'=' * 60}")
|
| 258 |
+
print("Results Summary:")
|
| 259 |
+
print(f"{'=' * 60}")
|
| 260 |
+
print(f"Average Naturalness Score: {avg_score:.4f}")
|
| 261 |
+
print(f"Number of videos evaluated: {len(scores)}")
|
| 262 |
+
print(f"Results saved to: {output_json_path}")
|
| 263 |
+
print(f"{'=' * 60}\n")
|
| 264 |
+
else:
|
| 265 |
+
print("No videos were successfully evaluated!")
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
if __name__ == "__main__":
|
| 269 |
+
parser = argparse.ArgumentParser(description="Evaluate video naturalness using VLM")
|
| 270 |
+
|
| 271 |
+
# Input/Output arguments
|
| 272 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 273 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 274 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 275 |
+
|
| 276 |
+
# API arguments
|
| 277 |
+
parser.add_argument("--api_key", type=str, required=True)
|
| 278 |
+
parser.add_argument("--model_name", type=str, default="gpt-5.2-2025-12-11")
|
| 279 |
+
parser.add_argument("--base_url", type=str, default=None)
|
| 280 |
+
|
| 281 |
+
# Evaluation arguments
|
| 282 |
+
parser.add_argument("--num_frames", type=int, default=16)
|
| 283 |
+
parser.add_argument("--num_workers", type=int, default=64)
|
| 284 |
+
|
| 285 |
+
args = parser.parse_args()
|
| 286 |
+
|
| 287 |
+
main(args)
|
Helios/eval/5_get_drifting_aesthetic.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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d
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
from utils.utils import clip_transform, load_video
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
BATCH_SIZE = 32
|
| 18 |
+
# Percentage of frames to use for start/end portions
|
| 19 |
+
DRIFT_RATIO = 0.15
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_aesthetic_model(path_to_model):
|
| 23 |
+
"""Load the aesthetic predictor model"""
|
| 24 |
+
m = nn.Linear(768, 1)
|
| 25 |
+
s = torch.load(path_to_model, map_location="cpu", weights_only=False)
|
| 26 |
+
m.load_state_dict(s)
|
| 27 |
+
m.eval()
|
| 28 |
+
return m
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def evaluate_aesthetic_on_frames(aesthetic_model, clip_model, frames, device):
|
| 32 |
+
"""Evaluate aesthetic on a set of frames"""
|
| 33 |
+
if len(frames) == 0:
|
| 34 |
+
return 0.0
|
| 35 |
+
|
| 36 |
+
aesthetic_model.eval()
|
| 37 |
+
clip_model.eval()
|
| 38 |
+
|
| 39 |
+
image_transform = clip_transform(224)
|
| 40 |
+
aesthetic_scores_list = []
|
| 41 |
+
|
| 42 |
+
# Process in batches
|
| 43 |
+
for i in range(0, len(frames), BATCH_SIZE):
|
| 44 |
+
frame_batch = frames[i : i + BATCH_SIZE]
|
| 45 |
+
frame_batch = image_transform(frame_batch)
|
| 46 |
+
frame_batch = frame_batch.to(device)
|
| 47 |
+
|
| 48 |
+
with torch.no_grad():
|
| 49 |
+
image_feats = clip_model.encode_image(frame_batch).to(torch.float32)
|
| 50 |
+
image_feats = F.normalize(image_feats, dim=-1, p=2)
|
| 51 |
+
aesthetic_scores = aesthetic_model(image_feats).squeeze(dim=-1)
|
| 52 |
+
|
| 53 |
+
aesthetic_scores_list.append(aesthetic_scores)
|
| 54 |
+
|
| 55 |
+
# Combine all scores
|
| 56 |
+
aesthetic_scores = torch.cat(aesthetic_scores_list, dim=0)
|
| 57 |
+
normalized_aesthetic_scores = aesthetic_scores / 10.0
|
| 58 |
+
avg_score = torch.mean(normalized_aesthetic_scores, dim=0, keepdim=True)
|
| 59 |
+
|
| 60 |
+
return avg_score.item()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def evaluate_drifting_aesthetic(aesthetic_model, clip_model, video_path, height=384, width=640, device="cuda"):
|
| 64 |
+
"""
|
| 65 |
+
Evaluate drifting aesthetic for a single video.
|
| 66 |
+
Returns: (drift_score, start_score, end_score)
|
| 67 |
+
"""
|
| 68 |
+
# Load video frames
|
| 69 |
+
images = load_video(video_path, height=height, width=width)
|
| 70 |
+
|
| 71 |
+
total_frames = len(images)
|
| 72 |
+
num_drift_frames = max(1, int(total_frames * DRIFT_RATIO))
|
| 73 |
+
|
| 74 |
+
# Extract start and end portions
|
| 75 |
+
start_frames = images[:num_drift_frames]
|
| 76 |
+
end_frames = images[-num_drift_frames:]
|
| 77 |
+
|
| 78 |
+
# Calculate scores for each portion
|
| 79 |
+
start_score = evaluate_aesthetic_on_frames(aesthetic_model, clip_model, start_frames, device)
|
| 80 |
+
end_score = evaluate_aesthetic_on_frames(aesthetic_model, clip_model, end_frames, device)
|
| 81 |
+
|
| 82 |
+
# Calculate drift as absolute difference
|
| 83 |
+
drift_score = abs(start_score - end_score)
|
| 84 |
+
|
| 85 |
+
return drift_score, start_score, end_score
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def main(args):
|
| 89 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 90 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 91 |
+
output_json_path = os.path.join(output_path, "drifting_aesthetic_results.json")
|
| 92 |
+
|
| 93 |
+
# Set device
|
| 94 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 95 |
+
print(f"Using device: {device}")
|
| 96 |
+
|
| 97 |
+
# Load CSV file
|
| 98 |
+
if not os.path.exists(args.input_csv):
|
| 99 |
+
raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
|
| 100 |
+
|
| 101 |
+
df = pd.read_csv(args.input_csv)
|
| 102 |
+
df_dict = df.set_index("id").to_dict("index")
|
| 103 |
+
|
| 104 |
+
# Validate CSV columns
|
| 105 |
+
required_columns = ["id", "duration"]
|
| 106 |
+
for col in required_columns:
|
| 107 |
+
if col not in df.columns:
|
| 108 |
+
raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
|
| 109 |
+
|
| 110 |
+
# Load existing results if available
|
| 111 |
+
existing_results = {}
|
| 112 |
+
if os.path.exists(output_json_path):
|
| 113 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 114 |
+
with open(output_json_path, "r") as f:
|
| 115 |
+
existing_data = json.load(f)
|
| 116 |
+
for item in existing_data.get("per_video_results", []):
|
| 117 |
+
existing_results[item["id"]] = item
|
| 118 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 119 |
+
|
| 120 |
+
# Get video files
|
| 121 |
+
video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
|
| 122 |
+
video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
|
| 123 |
+
print(f"\nFound {len(video_files)} videos in directory")
|
| 124 |
+
|
| 125 |
+
# Check which videos need processing
|
| 126 |
+
results = []
|
| 127 |
+
drift_scores = []
|
| 128 |
+
videos_to_process = []
|
| 129 |
+
|
| 130 |
+
for video_path in video_files:
|
| 131 |
+
video_name = os.path.basename(video_path)
|
| 132 |
+
parts = video_name.replace(".mp4", "").split("_")
|
| 133 |
+
video_id = int(parts[0])
|
| 134 |
+
|
| 135 |
+
if video_id not in df_dict:
|
| 136 |
+
print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
|
| 137 |
+
continue
|
| 138 |
+
|
| 139 |
+
# Check if already processed
|
| 140 |
+
if video_id in existing_results:
|
| 141 |
+
# Use existing result
|
| 142 |
+
results.append(existing_results[video_id])
|
| 143 |
+
drift_scores.append(existing_results[video_id]["drift_aesthetic_score"])
|
| 144 |
+
else:
|
| 145 |
+
# Need to process
|
| 146 |
+
videos_to_process.append((video_path, video_id, video_name))
|
| 147 |
+
|
| 148 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 149 |
+
print(f"Need to process: {len(videos_to_process)} videos")
|
| 150 |
+
|
| 151 |
+
# Process remaining videos
|
| 152 |
+
if videos_to_process:
|
| 153 |
+
# Load models
|
| 154 |
+
print("Loading CLIP model...")
|
| 155 |
+
clip_model, preprocess = clip.load(args.clip_model_path, device=device)
|
| 156 |
+
|
| 157 |
+
print("Loading aesthetic predictor model...")
|
| 158 |
+
aesthetic_model = get_aesthetic_model(args.aesthetic_model_path).to(device)
|
| 159 |
+
|
| 160 |
+
print("\nEvaluating remaining videos...")
|
| 161 |
+
for video_path, video_id, video_name in tqdm(videos_to_process):
|
| 162 |
+
try:
|
| 163 |
+
drift_score, start_score, end_score = evaluate_drifting_aesthetic(
|
| 164 |
+
aesthetic_model,
|
| 165 |
+
clip_model,
|
| 166 |
+
video_path,
|
| 167 |
+
height=args.height,
|
| 168 |
+
width=args.width,
|
| 169 |
+
device=device,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
result_item = {
|
| 173 |
+
"id": video_id,
|
| 174 |
+
"video_name": video_name,
|
| 175 |
+
"drift_aesthetic_score": drift_score,
|
| 176 |
+
"start_aesthetic_score": start_score,
|
| 177 |
+
"end_aesthetic_score": end_score,
|
| 178 |
+
}
|
| 179 |
+
results.append(result_item)
|
| 180 |
+
drift_scores.append(drift_score)
|
| 181 |
+
|
| 182 |
+
except Exception as e:
|
| 183 |
+
print(f"Error processing {video_name}: {str(e)}")
|
| 184 |
+
continue
|
| 185 |
+
else:
|
| 186 |
+
print("No videos to process. Skipping evaluation.")
|
| 187 |
+
return
|
| 188 |
+
|
| 189 |
+
# Sort all results by video_id
|
| 190 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 191 |
+
|
| 192 |
+
# Calculate overall metrics
|
| 193 |
+
if drift_scores:
|
| 194 |
+
avg_drift = sum(drift_scores) / len(drift_scores)
|
| 195 |
+
|
| 196 |
+
output = {
|
| 197 |
+
"metric": "drifting_aesthetic",
|
| 198 |
+
"description": f"Start-end contrast of aesthetic (first/last {DRIFT_RATIO * 100:.0f}% frames)",
|
| 199 |
+
"average_drift_score": avg_drift,
|
| 200 |
+
"num_videos": len(drift_scores),
|
| 201 |
+
"per_video_results": results_sorted,
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
# Save results
|
| 205 |
+
os.makedirs(output_path, exist_ok=True)
|
| 206 |
+
with open(output_json_path, "w") as f:
|
| 207 |
+
json.dump(output, f, indent=2)
|
| 208 |
+
|
| 209 |
+
print(f"\n{'=' * 60}")
|
| 210 |
+
print("Results Summary:")
|
| 211 |
+
print(f"{'=' * 60}")
|
| 212 |
+
print(f"Average Drifting Aesthetic Score: {avg_drift:.4f}")
|
| 213 |
+
print("(Lower is better - indicates less quality drift)")
|
| 214 |
+
print(f"Number of videos evaluated: {len(drift_scores)}")
|
| 215 |
+
print(f"Results saved to: {output_json_path}")
|
| 216 |
+
print(f"{'=' * 60}\n")
|
| 217 |
+
else:
|
| 218 |
+
print("No videos were successfully evaluated!")
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
parser = argparse.ArgumentParser(description="Evaluate drifting aesthetic using CLIP + LAION aesthetic predictor")
|
| 223 |
+
|
| 224 |
+
# Input/Output arguments
|
| 225 |
+
parser.add_argument("--height", type=str, default=384)
|
| 226 |
+
parser.add_argument("--width", type=str, default=640)
|
| 227 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 228 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 229 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 230 |
+
|
| 231 |
+
# Model arguments
|
| 232 |
+
parser.add_argument("--clip_model_path", type=str, default="checkpoints/aesthetic_model/ViT-L-14.pt")
|
| 233 |
+
parser.add_argument(
|
| 234 |
+
"--aesthetic_model_path", type=str, default="checkpoints/aesthetic_model/sa_0_4_vit_l_14_linear.pth"
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
args = parser.parse_args()
|
| 238 |
+
|
| 239 |
+
main(args)
|
Helios/eval/6_get_drifting_motion_smoothness.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import glob
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import torch
|
| 11 |
+
from omegaconf import OmegaConf
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
from utils.third_party.amt.utils.build_utils import build_from_cfg
|
| 15 |
+
from utils.third_party.amt.utils.utils import InputPadder, check_dim_and_resize, img2tensor, tensor2img
|
| 16 |
+
from utils.utils import align_dimension
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# Percentage of frames to use for start/end portions
|
| 20 |
+
DRIFT_RATIO = 0.15
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class FrameProcess:
|
| 24 |
+
def __init__(self, height=384, width=640):
|
| 25 |
+
self.height = height
|
| 26 |
+
self.width = width
|
| 27 |
+
|
| 28 |
+
def get_frames(self, video_path):
|
| 29 |
+
"""Extract frames from MP4 video"""
|
| 30 |
+
frame_list = []
|
| 31 |
+
video = cv2.VideoCapture(video_path)
|
| 32 |
+
|
| 33 |
+
original_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 34 |
+
original_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 35 |
+
original_aspect_ratio = original_width / original_height
|
| 36 |
+
|
| 37 |
+
if self.width > self.height:
|
| 38 |
+
target_width = self.width
|
| 39 |
+
target_height = int(self.width / original_aspect_ratio)
|
| 40 |
+
else:
|
| 41 |
+
target_height = self.height
|
| 42 |
+
target_width = int(self.height * original_aspect_ratio)
|
| 43 |
+
|
| 44 |
+
target_height = align_dimension(target_height, 2)
|
| 45 |
+
target_width = align_dimension(target_width, 2)
|
| 46 |
+
|
| 47 |
+
while video.isOpened():
|
| 48 |
+
success, frame = video.read()
|
| 49 |
+
if success:
|
| 50 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 51 |
+
frame = cv2.resize(frame, (target_width, target_height))
|
| 52 |
+
frame_list.append(frame)
|
| 53 |
+
else:
|
| 54 |
+
break
|
| 55 |
+
video.release()
|
| 56 |
+
assert frame_list != [], "No frames extracted from video"
|
| 57 |
+
return frame_list
|
| 58 |
+
|
| 59 |
+
def extract_frame(self, frame_list, start_from=0):
|
| 60 |
+
extract = []
|
| 61 |
+
for i in range(start_from, len(frame_list), 2):
|
| 62 |
+
extract.append(frame_list[i])
|
| 63 |
+
return extract
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class MotionSmoothnessEvaluator:
|
| 67 |
+
def __init__(self, config, ckpt, height=384, width=640, device="cuda"):
|
| 68 |
+
self.device = device
|
| 69 |
+
self.config = config
|
| 70 |
+
self.ckpt = ckpt
|
| 71 |
+
self.niters = 1
|
| 72 |
+
self.height = height
|
| 73 |
+
self.width = width
|
| 74 |
+
self.initialization()
|
| 75 |
+
self.load_model()
|
| 76 |
+
|
| 77 |
+
def load_model(self):
|
| 78 |
+
"""Load AMT model"""
|
| 79 |
+
cfg_path = self.config
|
| 80 |
+
ckpt_path = self.ckpt
|
| 81 |
+
network_cfg = OmegaConf.load(cfg_path).network
|
| 82 |
+
network_name = network_cfg.name
|
| 83 |
+
print(f"Loading [{network_name}] from [{ckpt_path}]...")
|
| 84 |
+
|
| 85 |
+
self.model = build_from_cfg(network_cfg)
|
| 86 |
+
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 87 |
+
self.model.load_state_dict(ckpt["state_dict"])
|
| 88 |
+
self.model = self.model.to(self.device)
|
| 89 |
+
self.model.eval()
|
| 90 |
+
|
| 91 |
+
def initialization(self):
|
| 92 |
+
"""Initialize parameters based on device"""
|
| 93 |
+
if self.device.type == "cuda":
|
| 94 |
+
self.anchor_resolution = 1024 * 512
|
| 95 |
+
self.anchor_memory = 1500 * 1024**2
|
| 96 |
+
self.anchor_memory_bias = 2500 * 1024**2
|
| 97 |
+
self.vram_avail = torch.cuda.get_device_properties(self.device).total_memory
|
| 98 |
+
else:
|
| 99 |
+
self.anchor_resolution = 8192 * 8192
|
| 100 |
+
self.anchor_memory = 1
|
| 101 |
+
self.anchor_memory_bias = 0
|
| 102 |
+
self.vram_avail = 1
|
| 103 |
+
|
| 104 |
+
self.embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(self.device)
|
| 105 |
+
self.fp = FrameProcess(height=self.height, width=self.width)
|
| 106 |
+
|
| 107 |
+
def compute_motion_score_on_frames(self, frames):
|
| 108 |
+
"""Calculate motion smoothness score for a list of frames"""
|
| 109 |
+
if len(frames) < 4:
|
| 110 |
+
return 0.0
|
| 111 |
+
|
| 112 |
+
frame_list = self.fp.extract_frame(frames, start_from=0)
|
| 113 |
+
if len(frame_list) < 2:
|
| 114 |
+
return 0.0
|
| 115 |
+
|
| 116 |
+
# Convert to tensors
|
| 117 |
+
inputs = [img2tensor(frame).to(self.device) for frame in frame_list]
|
| 118 |
+
|
| 119 |
+
inputs = check_dim_and_resize(inputs)
|
| 120 |
+
h, w = inputs[0].shape[-2:]
|
| 121 |
+
scale = (
|
| 122 |
+
self.anchor_resolution
|
| 123 |
+
/ (h * w)
|
| 124 |
+
* np.sqrt((self.vram_avail - self.anchor_memory_bias) / self.anchor_memory)
|
| 125 |
+
)
|
| 126 |
+
scale = 1 if scale > 1 else scale
|
| 127 |
+
scale = 1 / np.floor(1 / np.sqrt(scale) * 16) * 16
|
| 128 |
+
|
| 129 |
+
padding = int(16 / scale)
|
| 130 |
+
padder = InputPadder(inputs[0].shape, padding)
|
| 131 |
+
inputs = padder.pad(*inputs)
|
| 132 |
+
|
| 133 |
+
# Frame interpolation
|
| 134 |
+
iters = int(self.niters)
|
| 135 |
+
for i in range(iters):
|
| 136 |
+
outputs = [inputs[0]]
|
| 137 |
+
for in_0, in_1 in zip(inputs[:-1], inputs[1:]):
|
| 138 |
+
in_0 = in_0.to(self.device)
|
| 139 |
+
in_1 = in_1.to(self.device)
|
| 140 |
+
with torch.no_grad():
|
| 141 |
+
imgt_pred = self.model(in_0, in_1, self.embt, scale_factor=scale, eval=True)["imgt_pred"]
|
| 142 |
+
outputs += [imgt_pred.cpu(), in_1.cpu()]
|
| 143 |
+
inputs = outputs
|
| 144 |
+
|
| 145 |
+
# Calculate VFI score
|
| 146 |
+
outputs = padder.unpad(*outputs)
|
| 147 |
+
outputs = [tensor2img(out) for out in outputs]
|
| 148 |
+
vfi_score = self.vfi_score(frames, outputs)
|
| 149 |
+
norm = (255.0 - vfi_score) / 255.0
|
| 150 |
+
|
| 151 |
+
return norm
|
| 152 |
+
|
| 153 |
+
def vfi_score(self, ori_frames, interpolate_frames):
|
| 154 |
+
"""Calculate video frame interpolation quality score"""
|
| 155 |
+
ori = self.fp.extract_frame(ori_frames, start_from=1)
|
| 156 |
+
interpolate = self.fp.extract_frame(interpolate_frames, start_from=1)
|
| 157 |
+
|
| 158 |
+
scores = []
|
| 159 |
+
min_len = min(len(ori), len(interpolate))
|
| 160 |
+
for i in range(min_len):
|
| 161 |
+
scores.append(self.get_diff(ori[i], interpolate[i]))
|
| 162 |
+
|
| 163 |
+
if len(scores) == 0:
|
| 164 |
+
return 0.0
|
| 165 |
+
return np.mean(np.array(scores))
|
| 166 |
+
|
| 167 |
+
def get_diff(self, img1, img2):
|
| 168 |
+
"""Calculate absolute difference between two images"""
|
| 169 |
+
img = cv2.absdiff(img1, img2)
|
| 170 |
+
return np.mean(img)
|
| 171 |
+
|
| 172 |
+
def evaluate_drifting(self, video_path):
|
| 173 |
+
"""
|
| 174 |
+
Evaluate drifting motion smoothness for a single video.
|
| 175 |
+
Returns: (drift_score, start_score, end_score)
|
| 176 |
+
"""
|
| 177 |
+
frames = self.fp.get_frames(video_path)
|
| 178 |
+
total_frames = len(frames)
|
| 179 |
+
num_drift_frames = max(4, int(total_frames * DRIFT_RATIO)) # Need at least 4 frames for AMT
|
| 180 |
+
|
| 181 |
+
# Extract start and end portions
|
| 182 |
+
start_frames = frames[:num_drift_frames]
|
| 183 |
+
end_frames = frames[-num_drift_frames:]
|
| 184 |
+
|
| 185 |
+
# Calculate scores for each portion
|
| 186 |
+
start_score = self.compute_motion_score_on_frames(start_frames)
|
| 187 |
+
end_score = self.compute_motion_score_on_frames(end_frames)
|
| 188 |
+
|
| 189 |
+
# Calculate drift as absolute difference
|
| 190 |
+
drift_score = abs(start_score - end_score)
|
| 191 |
+
|
| 192 |
+
return drift_score, start_score, end_score
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def main(args):
|
| 196 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 197 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 198 |
+
output_json_path = os.path.join(output_path, "drifting_motion_smoothness_results.json")
|
| 199 |
+
|
| 200 |
+
# Set device
|
| 201 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 202 |
+
print(f"Using device: {device}")
|
| 203 |
+
|
| 204 |
+
# Load CSV file
|
| 205 |
+
if not os.path.exists(args.input_csv):
|
| 206 |
+
raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
|
| 207 |
+
|
| 208 |
+
df = pd.read_csv(args.input_csv)
|
| 209 |
+
df_dict = df.set_index("id").to_dict("index")
|
| 210 |
+
|
| 211 |
+
# Validate CSV columns
|
| 212 |
+
required_columns = ["id", "duration"]
|
| 213 |
+
for col in required_columns:
|
| 214 |
+
if col not in df.columns:
|
| 215 |
+
raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
|
| 216 |
+
|
| 217 |
+
# Load existing results if available
|
| 218 |
+
existing_results = {}
|
| 219 |
+
if os.path.exists(output_json_path):
|
| 220 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 221 |
+
with open(output_json_path, "r") as f:
|
| 222 |
+
existing_data = json.load(f)
|
| 223 |
+
for item in existing_data.get("per_video_results", []):
|
| 224 |
+
existing_results[item["id"]] = item
|
| 225 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 226 |
+
|
| 227 |
+
# Get video files
|
| 228 |
+
video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
|
| 229 |
+
video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
|
| 230 |
+
print(f"\nFound {len(video_files)} videos in directory")
|
| 231 |
+
|
| 232 |
+
# Check which videos need processing
|
| 233 |
+
results = []
|
| 234 |
+
drift_scores = []
|
| 235 |
+
videos_to_process = []
|
| 236 |
+
|
| 237 |
+
for video_path in video_files:
|
| 238 |
+
video_name = os.path.basename(video_path)
|
| 239 |
+
parts = video_name.replace(".mp4", "").split("_")
|
| 240 |
+
video_id = int(parts[0])
|
| 241 |
+
|
| 242 |
+
if video_id not in df_dict:
|
| 243 |
+
print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
|
| 244 |
+
continue
|
| 245 |
+
|
| 246 |
+
# Check if already processed
|
| 247 |
+
if video_id in existing_results:
|
| 248 |
+
# Use existing result
|
| 249 |
+
results.append(existing_results[video_id])
|
| 250 |
+
drift_scores.append(existing_results[video_id]["drift_motion_smoothness_score"])
|
| 251 |
+
else:
|
| 252 |
+
# Need to process
|
| 253 |
+
videos_to_process.append((video_path, video_id, video_name))
|
| 254 |
+
|
| 255 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 256 |
+
print(f"Need to process: {len(videos_to_process)} videos")
|
| 257 |
+
|
| 258 |
+
# Process remaining videos
|
| 259 |
+
if videos_to_process:
|
| 260 |
+
# Load model
|
| 261 |
+
print("Loading AMT model...")
|
| 262 |
+
evaluator = MotionSmoothnessEvaluator(
|
| 263 |
+
args.config, args.smoothness_model_path, height=args.height, width=args.width, device=device
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
print("\nEvaluating remaining videos...")
|
| 267 |
+
for video_path, video_id, video_name in tqdm(videos_to_process):
|
| 268 |
+
try:
|
| 269 |
+
drift_score, start_score, end_score = evaluator.evaluate_drifting(video_path)
|
| 270 |
+
|
| 271 |
+
result_item = {
|
| 272 |
+
"id": video_id,
|
| 273 |
+
"video_name": video_name,
|
| 274 |
+
"drift_motion_smoothness_score": float(drift_score),
|
| 275 |
+
"start_motion_smoothness_score": float(start_score),
|
| 276 |
+
"end_motion_smoothness_score": float(end_score),
|
| 277 |
+
}
|
| 278 |
+
results.append(result_item)
|
| 279 |
+
drift_scores.append(drift_score)
|
| 280 |
+
|
| 281 |
+
except Exception as e:
|
| 282 |
+
print(f"Error processing {video_name}: {str(e)}")
|
| 283 |
+
continue
|
| 284 |
+
else:
|
| 285 |
+
print("No videos to process. Skipping evaluation.")
|
| 286 |
+
return
|
| 287 |
+
|
| 288 |
+
# Sort all results by video_id
|
| 289 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 290 |
+
|
| 291 |
+
# Calculate overall metrics
|
| 292 |
+
if drift_scores:
|
| 293 |
+
avg_drift = sum(drift_scores) / len(drift_scores)
|
| 294 |
+
|
| 295 |
+
output = {
|
| 296 |
+
"metric": "drifting_motion_smoothness",
|
| 297 |
+
"description": f"Start-end contrast of motion smoothness (first/last {DRIFT_RATIO * 100:.0f}% frames)",
|
| 298 |
+
"average_drift_score": avg_drift,
|
| 299 |
+
"num_videos": len(drift_scores),
|
| 300 |
+
"per_video_results": results_sorted,
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
# Save results
|
| 304 |
+
os.makedirs(output_path, exist_ok=True)
|
| 305 |
+
with open(output_json_path, "w") as f:
|
| 306 |
+
json.dump(output, f, indent=2)
|
| 307 |
+
|
| 308 |
+
print(f"\n{'=' * 60}")
|
| 309 |
+
print("Results Summary:")
|
| 310 |
+
print(f"{'=' * 60}")
|
| 311 |
+
print(f"Average Drifting Motion Smoothness Score: {avg_drift:.4f}")
|
| 312 |
+
print("(Lower is better - indicates less motion quality drift)")
|
| 313 |
+
print(f"Number of videos evaluated: {len(drift_scores)}")
|
| 314 |
+
print(f"Results saved to: {output_json_path}")
|
| 315 |
+
print(f"{'=' * 60}\n")
|
| 316 |
+
else:
|
| 317 |
+
print("No videos were successfully evaluated!")
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
if __name__ == "__main__":
|
| 321 |
+
parser = argparse.ArgumentParser(description="Evaluate drifting motion smoothness using AMT model")
|
| 322 |
+
|
| 323 |
+
# Input/Output arguments
|
| 324 |
+
parser.add_argument("--height", type=str, default=384)
|
| 325 |
+
parser.add_argument("--width", type=str, default=640)
|
| 326 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 327 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 328 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 329 |
+
|
| 330 |
+
# Model arguments
|
| 331 |
+
parser.add_argument("--config", type=str, default="checkpoints/AMT-S.yaml")
|
| 332 |
+
parser.add_argument("--smoothness_model_path", type=str, default="checkpoints/amt_model/amt-s.pth")
|
| 333 |
+
|
| 334 |
+
args = parser.parse_args()
|
| 335 |
+
|
| 336 |
+
main(args)
|
Helios/eval/7_get_drifting_semantic.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import glob
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import torch
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
from utils.third_party.ViCLIP.simple_tokenizer import SimpleTokenizer
|
| 12 |
+
from utils.third_party.ViCLIP.viclip import ViCLIP
|
| 13 |
+
from utils.utils import clip_transform, load_video_frames
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Percentage of frames to use for start/end portions
|
| 17 |
+
DRIFT_RATIO = 0.15
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_text_features(model, input_text, tokenizer, text_feature_dict={}):
|
| 21 |
+
"""Get text features from ViCLIP"""
|
| 22 |
+
if input_text in text_feature_dict:
|
| 23 |
+
return text_feature_dict[input_text]
|
| 24 |
+
|
| 25 |
+
text_template = f"{input_text}"
|
| 26 |
+
with torch.no_grad():
|
| 27 |
+
text_features = model.encode_text(text_template).float()
|
| 28 |
+
text_features /= text_features.norm(dim=-1, keepdim=True)
|
| 29 |
+
text_feature_dict[input_text] = text_features
|
| 30 |
+
|
| 31 |
+
return text_features
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_vid_features(model, input_frames):
|
| 35 |
+
"""Get video features from ViCLIP"""
|
| 36 |
+
with torch.no_grad():
|
| 37 |
+
clip_feat = model.encode_vision(input_frames, test=True).float()
|
| 38 |
+
clip_feat /= clip_feat.norm(dim=-1, keepdim=True)
|
| 39 |
+
return clip_feat
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def evaluate_semantic_on_portion(
|
| 43 |
+
model,
|
| 44 |
+
tokenizer,
|
| 45 |
+
video_path,
|
| 46 |
+
prompt,
|
| 47 |
+
height=384,
|
| 48 |
+
width=640,
|
| 49 |
+
device="cuda",
|
| 50 |
+
start_ratio=0.0,
|
| 51 |
+
end_ratio=DRIFT_RATIO,
|
| 52 |
+
num_frames=8,
|
| 53 |
+
):
|
| 54 |
+
"""Evaluate semantic consistency on a portion of the video"""
|
| 55 |
+
image_transform = clip_transform(224)
|
| 56 |
+
|
| 57 |
+
with torch.no_grad():
|
| 58 |
+
# Load video frames from the specified portion
|
| 59 |
+
images = load_video_frames(
|
| 60 |
+
video_path, start_ratio, end_ratio, num_frames=num_frames, height=height, width=width
|
| 61 |
+
)
|
| 62 |
+
images = image_transform(images)
|
| 63 |
+
images = images.to(device)
|
| 64 |
+
|
| 65 |
+
# Get features
|
| 66 |
+
clip_feat = get_vid_features(model, images.unsqueeze(0))
|
| 67 |
+
text_feat = get_text_features(model, prompt, tokenizer)
|
| 68 |
+
|
| 69 |
+
# Calculate similarity
|
| 70 |
+
logit_per_text = clip_feat @ text_feat.T
|
| 71 |
+
score = float(logit_per_text[0][0].cpu())
|
| 72 |
+
|
| 73 |
+
return score
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def evaluate_drifting_semantic(model, tokenizer, video_path, prompt, height=384, width=640, device="cuda"):
|
| 77 |
+
"""
|
| 78 |
+
Evaluate drifting semantic consistency for a single video.
|
| 79 |
+
Returns: (drift_score, start_score, end_score)
|
| 80 |
+
"""
|
| 81 |
+
# Evaluate start portion (first 15%)
|
| 82 |
+
start_score = evaluate_semantic_on_portion(
|
| 83 |
+
model,
|
| 84 |
+
tokenizer,
|
| 85 |
+
video_path,
|
| 86 |
+
prompt,
|
| 87 |
+
height=height,
|
| 88 |
+
width=width,
|
| 89 |
+
device=device,
|
| 90 |
+
start_ratio=0.0,
|
| 91 |
+
end_ratio=DRIFT_RATIO,
|
| 92 |
+
num_frames=8,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
# Evaluate end portion (last 15%)
|
| 96 |
+
end_score = evaluate_semantic_on_portion(
|
| 97 |
+
model,
|
| 98 |
+
tokenizer,
|
| 99 |
+
video_path,
|
| 100 |
+
prompt,
|
| 101 |
+
height=height,
|
| 102 |
+
width=width,
|
| 103 |
+
device=device,
|
| 104 |
+
start_ratio=1.0 - DRIFT_RATIO,
|
| 105 |
+
end_ratio=1.0,
|
| 106 |
+
num_frames=8,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Calculate drift as absolute difference
|
| 110 |
+
drift_score = abs(start_score - end_score)
|
| 111 |
+
|
| 112 |
+
return drift_score, start_score, end_score
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def main(args):
|
| 116 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 117 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 118 |
+
output_json_path = os.path.join(output_path, "drifting_semantic_results.json")
|
| 119 |
+
|
| 120 |
+
# Set device
|
| 121 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 122 |
+
print(f"Using device: {device}")
|
| 123 |
+
|
| 124 |
+
# Load CSV file
|
| 125 |
+
if not os.path.exists(args.input_csv):
|
| 126 |
+
raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
|
| 127 |
+
|
| 128 |
+
df = pd.read_csv(args.input_csv)
|
| 129 |
+
df_dict = df.set_index("id").to_dict("index")
|
| 130 |
+
|
| 131 |
+
# Validate CSV columns
|
| 132 |
+
required_columns = ["id", "duration", "prompt"]
|
| 133 |
+
for col in required_columns:
|
| 134 |
+
if col not in df.columns:
|
| 135 |
+
raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
|
| 136 |
+
|
| 137 |
+
# Load existing results if available
|
| 138 |
+
existing_results = {}
|
| 139 |
+
if os.path.exists(output_json_path):
|
| 140 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 141 |
+
with open(output_json_path, "r") as f:
|
| 142 |
+
existing_data = json.load(f)
|
| 143 |
+
for item in existing_data.get("per_video_results", []):
|
| 144 |
+
existing_results[item["id"]] = item
|
| 145 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 146 |
+
|
| 147 |
+
# Get video files
|
| 148 |
+
video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
|
| 149 |
+
video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
|
| 150 |
+
print(f"\nFound {len(video_files)} videos in directory")
|
| 151 |
+
|
| 152 |
+
# Check which videos need processing
|
| 153 |
+
results = []
|
| 154 |
+
drift_scores = []
|
| 155 |
+
videos_to_process = []
|
| 156 |
+
|
| 157 |
+
for video_path in video_files:
|
| 158 |
+
video_name = os.path.basename(video_path)
|
| 159 |
+
parts = video_name.replace(".mp4", "").split("_")
|
| 160 |
+
video_id = int(parts[0])
|
| 161 |
+
|
| 162 |
+
if video_id not in df_dict:
|
| 163 |
+
print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
|
| 164 |
+
continue
|
| 165 |
+
|
| 166 |
+
# Check if already processed
|
| 167 |
+
if video_id in existing_results:
|
| 168 |
+
# Use existing result
|
| 169 |
+
results.append(existing_results[video_id])
|
| 170 |
+
drift_scores.append(existing_results[video_id]["drift_semantic_score"])
|
| 171 |
+
else:
|
| 172 |
+
# Need to process
|
| 173 |
+
prompt = df_dict[video_id]["prompt"]
|
| 174 |
+
videos_to_process.append((video_path, video_id, video_name, prompt))
|
| 175 |
+
|
| 176 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 177 |
+
print(f"Need to process: {len(videos_to_process)} videos")
|
| 178 |
+
|
| 179 |
+
# Process remaining videos
|
| 180 |
+
if videos_to_process:
|
| 181 |
+
# Load ViCLIP model
|
| 182 |
+
print("Loading ViCLIP model...")
|
| 183 |
+
tokenizer_path = os.path.join(args.semantic_model_path, "bpe_simple_vocab_16e6.txt.gz")
|
| 184 |
+
semantic_model_path = os.path.join(args.semantic_model_path, "ViClip-InternVid-10M-FLT.pth")
|
| 185 |
+
|
| 186 |
+
tokenizer = SimpleTokenizer(tokenizer_path)
|
| 187 |
+
viclip = ViCLIP(tokenizer=tokenizer, pretrain=semantic_model_path).to(device)
|
| 188 |
+
viclip.eval()
|
| 189 |
+
|
| 190 |
+
print("\nEvaluating remaining videos...")
|
| 191 |
+
for video_path, video_id, video_name, prompt in tqdm(videos_to_process):
|
| 192 |
+
try:
|
| 193 |
+
drift_score, start_score, end_score = evaluate_drifting_semantic(
|
| 194 |
+
viclip,
|
| 195 |
+
tokenizer,
|
| 196 |
+
video_path,
|
| 197 |
+
prompt,
|
| 198 |
+
height=args.height,
|
| 199 |
+
width=args.width,
|
| 200 |
+
device=device,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
result_item = {
|
| 204 |
+
"id": video_id,
|
| 205 |
+
"video_name": video_name,
|
| 206 |
+
"prompt": prompt,
|
| 207 |
+
"drift_semantic_score": drift_score,
|
| 208 |
+
"start_semantic_score": start_score,
|
| 209 |
+
"end_semantic_score": end_score,
|
| 210 |
+
}
|
| 211 |
+
results.append(result_item)
|
| 212 |
+
drift_scores.append(drift_score)
|
| 213 |
+
|
| 214 |
+
except Exception as e:
|
| 215 |
+
print(f"Error processing {video_name}: {str(e)}")
|
| 216 |
+
continue
|
| 217 |
+
else:
|
| 218 |
+
print("No videos to process. Skipping evaluation.")
|
| 219 |
+
return
|
| 220 |
+
|
| 221 |
+
# Sort all results by video_id
|
| 222 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 223 |
+
|
| 224 |
+
# Calculate overall metrics
|
| 225 |
+
if drift_scores:
|
| 226 |
+
avg_drift = sum(drift_scores) / len(drift_scores)
|
| 227 |
+
|
| 228 |
+
output = {
|
| 229 |
+
"metric": "drifting_semantic",
|
| 230 |
+
"description": f"Start-end contrast of semantic consistency (first/last {DRIFT_RATIO * 100:.0f}% frames)",
|
| 231 |
+
"average_drift_score": avg_drift,
|
| 232 |
+
"num_videos": len(drift_scores),
|
| 233 |
+
"per_video_results": results_sorted,
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
# Save results
|
| 237 |
+
os.makedirs(output_path, exist_ok=True)
|
| 238 |
+
with open(output_json_path, "w") as f:
|
| 239 |
+
json.dump(output, f, indent=2)
|
| 240 |
+
|
| 241 |
+
print(f"\n{'=' * 60}")
|
| 242 |
+
print("Results Summary:")
|
| 243 |
+
print(f"{'=' * 60}")
|
| 244 |
+
print(f"Average Drifting Semantic Score: {avg_drift:.4f}")
|
| 245 |
+
print("(Lower is better - indicates less semantic drift)")
|
| 246 |
+
print(f"Number of videos evaluated: {len(drift_scores)}")
|
| 247 |
+
print(f"Results saved to: {output_json_path}")
|
| 248 |
+
print(f"{'=' * 60}\n")
|
| 249 |
+
else:
|
| 250 |
+
print("No videos were successfully evaluated!")
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
parser = argparse.ArgumentParser(description="Evaluate drifting semantic consistency using ViCLIP model")
|
| 255 |
+
|
| 256 |
+
# Input/Output arguments
|
| 257 |
+
parser.add_argument("--height", type=str, default=384)
|
| 258 |
+
parser.add_argument("--width", type=str, default=640)
|
| 259 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 260 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 261 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 262 |
+
|
| 263 |
+
# Model arguments
|
| 264 |
+
parser.add_argument("--semantic_model_path", type=str, default="checkpoints/ViCLIP")
|
| 265 |
+
|
| 266 |
+
args = parser.parse_args()
|
| 267 |
+
|
| 268 |
+
main(args)
|
Helios/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import base64
|
| 3 |
+
import glob
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 8 |
+
|
| 9 |
+
import cv2
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from openai import OpenAI
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# Percentage of frames to use for start/end portions
|
| 16 |
+
DRIFT_RATIO = 0.15
|
| 17 |
+
|
| 18 |
+
PROMPT_VIDEO_DETECTION = """
|
| 19 |
+
Your task is to analyze ##NUM_FRAMES## frames sampled across a long video (e.g., ~1500 frames) to determine if it is AI-generated.
|
| 20 |
+
|
| 21 |
+
### CONTEXT:
|
| 22 |
+
Frames are sampled at wide intervals. Scene changes or camera movements are expected. Focus on individual frame integrity and local physical logic rather than global consistency.
|
| 23 |
+
|
| 24 |
+
### EVALUATION CRITERIA:
|
| 25 |
+
1. **Single-Frame Technical Flaws**: Look for AI-specific rendering "hallucinations":
|
| 26 |
+
- **Textures**: "Melting" surfaces, plastic-like skin, or chaotic patterns in complex areas (e.g., water ripples, foliage, fire).
|
| 27 |
+
- **Edges**: Unnatural blurring or "auras" around moving subjects where they meet the background.
|
| 28 |
+
2. **Local Physical Logic**: Within any given frame or small cluster of frames:
|
| 29 |
+
- Do shadows and reflections align with the visible light sources?
|
| 30 |
+
- Are objects interacting naturally with their environment (e.g., feet touching the ground properly, hands grasping objects correctly)?
|
| 31 |
+
3. **Biological Anomalies**: If humans appear, inspect for:
|
| 32 |
+
- Anatomical errors: Extra fingers, asymmetric eyes, or "fused" teeth.
|
| 33 |
+
- Unnatural micro-expressions or "dead" eyes lacking specular highlights.
|
| 34 |
+
4. **Transient Artifacts**: Even in sparse samples, look for "ghosting" or objects that seem to be partially transparent or merging with other objects (common in AI diffusion).
|
| 35 |
+
|
| 36 |
+
### SCORING SCALE:
|
| 37 |
+
- 1 (Definitely AI): Clear anatomical deformities, "melting" textures, or impossible physical interactions.
|
| 38 |
+
- 2 (Likely AI): Presence of "uncanny valley" effects, suspicious texture smoothing, or minor physical illogic.
|
| 39 |
+
- 3 (Uncertain): Ambiguous; could be low-quality real-world footage, heavy motion blur, or high-end AI.
|
| 40 |
+
- 4 (Likely Real): Consistent organic details, natural motion blur, and logical lighting.
|
| 41 |
+
- 5 (Definitely Real): Perfect high-frequency details (pores, fabric, grain), flawless physics, and natural anatomy.
|
| 42 |
+
|
| 43 |
+
### OUTPUT INSTRUCTION:
|
| 44 |
+
Return ONLY the integer score (1-5). No explanation.
|
| 45 |
+
""".strip()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def image_to_base64(image):
|
| 49 |
+
"""Convert image to base64 string"""
|
| 50 |
+
_, buffer = cv2.imencode(".jpg", image)
|
| 51 |
+
return base64.b64encode(buffer).decode("utf-8")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def resize_long_side(image, target_long=512):
|
| 55 |
+
"""Resize image keeping aspect ratio"""
|
| 56 |
+
h, w = image.shape[:2]
|
| 57 |
+
if h >= w:
|
| 58 |
+
new_h = target_long
|
| 59 |
+
new_w = int(w * target_long / h)
|
| 60 |
+
else:
|
| 61 |
+
new_w = target_long
|
| 62 |
+
new_h = int(h * target_long / w)
|
| 63 |
+
return cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def extract_frames_from_portion(video_path, num_frames=8, portion="start"):
|
| 67 |
+
"""
|
| 68 |
+
Extract frames from start or end portion of video
|
| 69 |
+
Args:
|
| 70 |
+
video_path: Path to video file
|
| 71 |
+
num_frames: Number of frames to extract
|
| 72 |
+
portion: 'start' or 'end'
|
| 73 |
+
"""
|
| 74 |
+
cap = cv2.VideoCapture(video_path)
|
| 75 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 76 |
+
|
| 77 |
+
# Calculate portion boundaries
|
| 78 |
+
num_drift_frames = max(1, int(total_frames * DRIFT_RATIO))
|
| 79 |
+
|
| 80 |
+
if portion == "start":
|
| 81 |
+
start_frame = 0
|
| 82 |
+
end_frame = num_drift_frames
|
| 83 |
+
else: # end
|
| 84 |
+
start_frame = total_frames - num_drift_frames
|
| 85 |
+
end_frame = total_frames
|
| 86 |
+
|
| 87 |
+
# Extract frames evenly from the portion
|
| 88 |
+
frame_interval = max((end_frame - start_frame) // num_frames, 1)
|
| 89 |
+
frames = []
|
| 90 |
+
|
| 91 |
+
for i in range(num_frames):
|
| 92 |
+
frame_idx = start_frame + i * frame_interval
|
| 93 |
+
if frame_idx >= end_frame:
|
| 94 |
+
break
|
| 95 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
|
| 96 |
+
ret, frame = cap.read()
|
| 97 |
+
if ret:
|
| 98 |
+
resized = resize_long_side(frame, 512)
|
| 99 |
+
frames.append(resized)
|
| 100 |
+
|
| 101 |
+
cap.release()
|
| 102 |
+
return frames
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def call_gpt(image_frames_base64, model_name, api_key, base_url, num_frames=8, temperature=0.0):
|
| 106 |
+
"""Call GPT API to evaluate video naturalness"""
|
| 107 |
+
client = OpenAI(api_key=api_key, base_url=base_url)
|
| 108 |
+
|
| 109 |
+
content_list = []
|
| 110 |
+
for frame in image_frames_base64:
|
| 111 |
+
content_list.append(
|
| 112 |
+
{
|
| 113 |
+
"type": "image_url",
|
| 114 |
+
"image_url": {"url": f"data:image/jpeg;base64,{frame}"},
|
| 115 |
+
}
|
| 116 |
+
)
|
| 117 |
+
content_list.append({"type": "text", "text": PROMPT_VIDEO_DETECTION.replace("##NUM_FRAMES##", str(num_frames))})
|
| 118 |
+
|
| 119 |
+
response = client.chat.completions.create(
|
| 120 |
+
model=model_name,
|
| 121 |
+
stream=False,
|
| 122 |
+
temperature=temperature,
|
| 123 |
+
messages=[{"role": "user", "content": content_list}],
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
score = response.choices[0].message.content.strip()
|
| 127 |
+
return score
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def evaluate_portion_naturalness(video_path, api_key, model_name, base_url, num_frames=8, portion="start"):
|
| 131 |
+
"""Evaluate naturalness for start or end portion of video"""
|
| 132 |
+
try:
|
| 133 |
+
frames = extract_frames_from_portion(video_path, num_frames, portion)
|
| 134 |
+
frames_base64 = [image_to_base64(f) for f in frames]
|
| 135 |
+
score_str = call_gpt(frames_base64, model_name, api_key, base_url, num_frames)
|
| 136 |
+
|
| 137 |
+
# Parse score
|
| 138 |
+
score = float(score_str)
|
| 139 |
+
score = max(1.0, min(5.0, score))
|
| 140 |
+
# Normalize to [0, 1] (1-5 to 0-1)
|
| 141 |
+
score = (score - 1) / 4.0
|
| 142 |
+
|
| 143 |
+
return score, score_str
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print(f"Error evaluating video portion {portion}: {str(e)}")
|
| 146 |
+
raise
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def evaluate_drifting_naturalness(video_path, api_key, model_name, base_url, num_frames=8):
|
| 150 |
+
"""
|
| 151 |
+
Evaluate drifting naturalness for a single video
|
| 152 |
+
Returns: (drift_score, start_score, end_score, start_raw, end_raw)
|
| 153 |
+
"""
|
| 154 |
+
# Evaluate start portion
|
| 155 |
+
start_score, start_raw = evaluate_portion_naturalness(
|
| 156 |
+
video_path, api_key, model_name, base_url, num_frames, portion="start"
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# Evaluate end portion
|
| 160 |
+
end_score, end_raw = evaluate_portion_naturalness(
|
| 161 |
+
video_path, api_key, model_name, base_url, num_frames, portion="end"
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# Calculate drift as absolute difference
|
| 165 |
+
drift_score = abs(start_score - end_score)
|
| 166 |
+
|
| 167 |
+
return drift_score, start_score, end_score, start_raw, end_raw
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def process_video_worker(args_tuple):
|
| 171 |
+
"""Worker function for parallel processing"""
|
| 172 |
+
video_path, video_id, video_name, api_key, model_name, base_url, num_frames = args_tuple
|
| 173 |
+
try:
|
| 174 |
+
drift_score, start_score, end_score, start_raw, end_raw = evaluate_drifting_naturalness(
|
| 175 |
+
video_path, api_key, model_name, base_url, num_frames
|
| 176 |
+
)
|
| 177 |
+
return {
|
| 178 |
+
"id": video_id,
|
| 179 |
+
"video_name": video_name,
|
| 180 |
+
"drift_naturalness_score": drift_score,
|
| 181 |
+
"start_naturalness_score": start_score,
|
| 182 |
+
"end_naturalness_score": end_score,
|
| 183 |
+
"start_raw_score": start_raw,
|
| 184 |
+
"end_raw_score": end_raw,
|
| 185 |
+
}
|
| 186 |
+
except Exception as e:
|
| 187 |
+
print(f"Error processing {video_name}: {str(e)}")
|
| 188 |
+
return None
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def main(args):
|
| 192 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 193 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 194 |
+
output_json_path = os.path.join(output_path, "drifting_naturalness_results.json")
|
| 195 |
+
|
| 196 |
+
print(f"Using API: {args.base_url}")
|
| 197 |
+
print(f"Model: {args.model_name}")
|
| 198 |
+
|
| 199 |
+
# Load CSV file
|
| 200 |
+
if not os.path.exists(args.input_csv):
|
| 201 |
+
raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
|
| 202 |
+
|
| 203 |
+
df = pd.read_csv(args.input_csv)
|
| 204 |
+
df_dict = df.set_index("id").to_dict("index")
|
| 205 |
+
|
| 206 |
+
# Validate CSV columns
|
| 207 |
+
required_columns = ["id", "duration"]
|
| 208 |
+
for col in required_columns:
|
| 209 |
+
if col not in df.columns:
|
| 210 |
+
raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
|
| 211 |
+
|
| 212 |
+
# Load existing results if available
|
| 213 |
+
existing_results = {}
|
| 214 |
+
if os.path.exists(output_json_path):
|
| 215 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 216 |
+
with open(output_json_path, "r") as f:
|
| 217 |
+
existing_data = json.load(f)
|
| 218 |
+
for item in existing_data.get("per_video_results", []):
|
| 219 |
+
existing_results[item["id"]] = item
|
| 220 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 221 |
+
|
| 222 |
+
# Get video files
|
| 223 |
+
video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
|
| 224 |
+
video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
|
| 225 |
+
print(f"\nFound {len(video_files)} videos in directory")
|
| 226 |
+
|
| 227 |
+
# Check which videos need processing
|
| 228 |
+
results = []
|
| 229 |
+
drift_scores = []
|
| 230 |
+
tasks = []
|
| 231 |
+
|
| 232 |
+
for video_path in video_files:
|
| 233 |
+
video_name = os.path.basename(video_path)
|
| 234 |
+
parts = video_name.replace(".mp4", "").split("_")
|
| 235 |
+
video_id = int(parts[0])
|
| 236 |
+
|
| 237 |
+
if video_id not in df_dict:
|
| 238 |
+
print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
|
| 239 |
+
continue
|
| 240 |
+
|
| 241 |
+
# Check if already processed
|
| 242 |
+
if video_id in existing_results:
|
| 243 |
+
# Use existing result
|
| 244 |
+
results.append(existing_results[video_id])
|
| 245 |
+
drift_scores.append(existing_results[video_id]["drift_naturalness_score"])
|
| 246 |
+
else:
|
| 247 |
+
# Need to process
|
| 248 |
+
tasks.append(
|
| 249 |
+
(
|
| 250 |
+
video_path,
|
| 251 |
+
video_id,
|
| 252 |
+
video_name,
|
| 253 |
+
args.api_key,
|
| 254 |
+
args.model_name,
|
| 255 |
+
args.base_url,
|
| 256 |
+
args.num_frames,
|
| 257 |
+
)
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 261 |
+
print(f"Need to process: {len(tasks)} videos")
|
| 262 |
+
|
| 263 |
+
# Evaluate remaining videos in parallel
|
| 264 |
+
if tasks:
|
| 265 |
+
results_dict = {}
|
| 266 |
+
|
| 267 |
+
print(f"Evaluating videos with {args.num_workers} workers...")
|
| 268 |
+
|
| 269 |
+
with ThreadPoolExecutor(max_workers=args.num_workers) as executor:
|
| 270 |
+
future_to_idx = {executor.submit(process_video_worker, task): idx for idx, task in enumerate(tasks)}
|
| 271 |
+
|
| 272 |
+
for future in tqdm(as_completed(future_to_idx), total=len(tasks), desc="Evaluating"):
|
| 273 |
+
idx = future_to_idx[future]
|
| 274 |
+
result = future.result()
|
| 275 |
+
if result is not None:
|
| 276 |
+
results_dict[idx] = result
|
| 277 |
+
|
| 278 |
+
# Add new results in order
|
| 279 |
+
new_results = [results_dict[i] for i in sorted(results_dict.keys())]
|
| 280 |
+
results.extend(new_results)
|
| 281 |
+
drift_scores.extend([r["drift_naturalness_score"] for r in new_results])
|
| 282 |
+
else:
|
| 283 |
+
print("No videos to process. Skipping evaluation.")
|
| 284 |
+
return
|
| 285 |
+
|
| 286 |
+
# Sort all results by video_id
|
| 287 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 288 |
+
|
| 289 |
+
# Calculate overall metrics and save final results
|
| 290 |
+
if drift_scores:
|
| 291 |
+
avg_drift = sum(drift_scores) / len(drift_scores)
|
| 292 |
+
|
| 293 |
+
output = {
|
| 294 |
+
"metric": "drifting_naturalness",
|
| 295 |
+
"description": f"Start-end contrast of naturalness (first/last {DRIFT_RATIO * 100:.0f}% frames)",
|
| 296 |
+
"average_drift_score": avg_drift,
|
| 297 |
+
"num_videos": len(drift_scores),
|
| 298 |
+
"model_name": args.model_name,
|
| 299 |
+
"per_video_results": results_sorted,
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
# Save results
|
| 303 |
+
os.makedirs(output_path, exist_ok=True)
|
| 304 |
+
|
| 305 |
+
with open(output_json_path, "w") as f:
|
| 306 |
+
json.dump(output, f, indent=2)
|
| 307 |
+
|
| 308 |
+
print(f"\n{'=' * 60}")
|
| 309 |
+
print("Results Summary:")
|
| 310 |
+
print(f"{'=' * 60}")
|
| 311 |
+
print(f"Average Drifting Naturalness Score: {avg_drift:.4f}")
|
| 312 |
+
print("(Lower is better - indicates less quality drift)")
|
| 313 |
+
print(f"Number of videos evaluated: {len(drift_scores)}")
|
| 314 |
+
print(f"Results saved to: {output_json_path}")
|
| 315 |
+
print(f"{'=' * 60}\n")
|
| 316 |
+
else:
|
| 317 |
+
print("No videos were successfully evaluated!")
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
if __name__ == "__main__":
|
| 321 |
+
parser = argparse.ArgumentParser(description="Evaluate drifting naturalness using VLM")
|
| 322 |
+
|
| 323 |
+
# Input/Output arguments
|
| 324 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 325 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 326 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 327 |
+
|
| 328 |
+
# API arguments
|
| 329 |
+
parser.add_argument("--api_key", type=str, required=True)
|
| 330 |
+
parser.add_argument("--model_name", type=str, default="gpt-5.2-2025-12-11")
|
| 331 |
+
parser.add_argument("--base_url", type=str, default=None)
|
| 332 |
+
|
| 333 |
+
# Evaluation arguments
|
| 334 |
+
parser.add_argument("--num_frames", type=int, default=16)
|
| 335 |
+
parser.add_argument("--num_workers", type=int, default=64)
|
| 336 |
+
|
| 337 |
+
args = parser.parse_args()
|
| 338 |
+
|
| 339 |
+
main(args)
|
Helios/eval/9_merge_all_scores.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
WEIGHTS_SHORT = {
|
| 7 |
+
"aesthetic": 0.10,
|
| 8 |
+
"motion_amplitude": 0.10,
|
| 9 |
+
"motion_smoothness": 0.10,
|
| 10 |
+
"semantic": 0.35,
|
| 11 |
+
"naturalness": 0.35,
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
WEIGHTS_LONG = {
|
| 15 |
+
"aesthetic": 0.03,
|
| 16 |
+
"motion_amplitude": 0.03,
|
| 17 |
+
"motion_smoothness": 0.03,
|
| 18 |
+
"semantic": 0.255,
|
| 19 |
+
"naturalness": 0.255,
|
| 20 |
+
"drifting_aesthetic": 0.099,
|
| 21 |
+
"drifting_motion_smoothness": 0.099,
|
| 22 |
+
"drifting_semantic": 0.099,
|
| 23 |
+
"drifting_naturalness": 0.099,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
METRIC_RANGES = {
|
| 28 |
+
"aesthetic": {"min": 0, "max": 1},
|
| 29 |
+
"motion_amplitude": {"min": 0, "max": 1},
|
| 30 |
+
"motion_smoothness": {"min": 0, "max": 1},
|
| 31 |
+
"naturalness": {"min": 0, "max": 1},
|
| 32 |
+
"semantic": {"min": 0, "max": 1},
|
| 33 |
+
"drifting_aesthetic": {"min": 0, "max": 1},
|
| 34 |
+
"drifting_motion_smoothness": {"min": 0, "max": 1},
|
| 35 |
+
"drifting_naturalness": {"min": 0, "max": 1},
|
| 36 |
+
"drifting_semantic": {"min": 0, "max": 1},
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
METRIC_ALIASES = {
|
| 40 |
+
"aesthetic_score": "aesthetic",
|
| 41 |
+
"motion_amplitude_score": "motion_amplitude",
|
| 42 |
+
"motion_smoothness_score": "motion_smoothness",
|
| 43 |
+
"naturalness_score": "naturalness",
|
| 44 |
+
"semantic_score": "semantic",
|
| 45 |
+
"drift_aesthetic_score": "drifting_aesthetic",
|
| 46 |
+
"drift_motion_smoothness_score": "drifting_motion_smoothness",
|
| 47 |
+
"drift_naturalness_score": "drifting_naturalness",
|
| 48 |
+
"drift_semantic_score": "drifting_semantic",
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
RATING_SCALE = 10
|
| 52 |
+
|
| 53 |
+
SCORING_RULES_SHORT = {
|
| 54 |
+
"aesthetic": {
|
| 55 |
+
"type": "higher_better",
|
| 56 |
+
"thresholds": [0.70, 0.65, 0.60, 0.55, 0.50, 0.45, 0.40, 0.35, 0.30],
|
| 57 |
+
},
|
| 58 |
+
"motion_amplitude": {
|
| 59 |
+
"type": "higher_better",
|
| 60 |
+
"thresholds": [0.45, 0.40, 0.35, 0.30, 0.25, 0.20, 0.15, 0.10, 0.05],
|
| 61 |
+
},
|
| 62 |
+
"motion_smoothness": {
|
| 63 |
+
"type": "higher_better",
|
| 64 |
+
"thresholds": [0.99, 0.98, 0.97, 0.96, 0.95, 0.94, 0.93, 0.92, 0.91],
|
| 65 |
+
},
|
| 66 |
+
"semantic": {"type": "higher_better", "thresholds": [0.30, 0.29, 0.28, 0.27, 0.26, 0.25, 0.24, 0.23, 0.22]},
|
| 67 |
+
"naturalness": {"type": "higher_better", "thresholds": [0.65, 0.60, 0.55, 0.50, 0.45, 0.40, 0.30, 0.25, 0.20]},
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
SCORING_RULES_LONG = {
|
| 71 |
+
"aesthetic": {
|
| 72 |
+
"type": "higher_better",
|
| 73 |
+
"thresholds": [0.70, 0.65, 0.60, 0.55, 0.50, 0.45, 0.40, 0.45, 0.40],
|
| 74 |
+
},
|
| 75 |
+
"motion_amplitude": {
|
| 76 |
+
"type": "higher_better",
|
| 77 |
+
"thresholds": [0.45, 0.40, 0.35, 0.30, 0.25, 0.20, 0.15, 0.10, 0.05],
|
| 78 |
+
},
|
| 79 |
+
"motion_smoothness": {
|
| 80 |
+
"type": "higher_better",
|
| 81 |
+
"thresholds": [0.99, 0.98, 0.97, 0.96, 0.95, 0.94, 0.93, 0.92, 0.91],
|
| 82 |
+
},
|
| 83 |
+
"semantic": {"type": "higher_better", "thresholds": [0.30, 0.29, 0.28, 0.27, 0.26, 0.25, 0.24, 0.23, 0.22]},
|
| 84 |
+
"naturalness": {"type": "higher_better", "thresholds": [0.65, 0.60, 0.55, 0.50, 0.45, 0.40, 0.30, 0.25, 0.20]},
|
| 85 |
+
"drifting_aesthetic": {
|
| 86 |
+
"type": "lower_better",
|
| 87 |
+
"thresholds": [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09],
|
| 88 |
+
},
|
| 89 |
+
"drifting_motion_smoothness": {
|
| 90 |
+
"type": "lower_better",
|
| 91 |
+
"thresholds": [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09],
|
| 92 |
+
},
|
| 93 |
+
"drifting_semantic": {
|
| 94 |
+
"type": "lower_better",
|
| 95 |
+
"thresholds": [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09],
|
| 96 |
+
},
|
| 97 |
+
"drifting_naturalness": {
|
| 98 |
+
"type": "lower_better",
|
| 99 |
+
"thresholds": [0.06, 0.08, 0.10, 0.12, 0.14, 0.16, 0.18, 0.20, 0.22],
|
| 100 |
+
},
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def calculate_weighted_rating(summary_data, is_long):
|
| 105 |
+
weights = WEIGHTS_LONG if is_long else WEIGHTS_SHORT
|
| 106 |
+
total_rating = 0.0
|
| 107 |
+
|
| 108 |
+
all_metrics = {**summary_data.get("non_drifting", {}), **summary_data.get("drifting", {})}
|
| 109 |
+
|
| 110 |
+
print(f"\nCalculating Weighted Total Rating ({'Long' if is_long else 'Short'}):")
|
| 111 |
+
for metric, weight in weights.items():
|
| 112 |
+
if metric in all_metrics and all_metrics[metric]["rating"] is not None:
|
| 113 |
+
contribution = all_metrics[metric]["rating"] * weight
|
| 114 |
+
total_rating += contribution
|
| 115 |
+
print(f" - {metric}: {all_metrics[metric]['rating']} * {weight} = {contribution:.4f}")
|
| 116 |
+
else:
|
| 117 |
+
print(f" ⚠ Warning: Metric '{metric}' missing for weighting!")
|
| 118 |
+
|
| 119 |
+
return round(total_rating, 4)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def convert_to_rating(normalized_score, metric_key, is_long):
|
| 123 |
+
if normalized_score is None:
|
| 124 |
+
return None
|
| 125 |
+
canonical_key = METRIC_ALIASES.get(metric_key, metric_key)
|
| 126 |
+
rule = SCORING_RULES_LONG[canonical_key] if is_long else SCORING_RULES_SHORT[canonical_key]
|
| 127 |
+
|
| 128 |
+
rule_type = rule["type"]
|
| 129 |
+
thresholds = rule["thresholds"]
|
| 130 |
+
|
| 131 |
+
if rule_type == "higher_better":
|
| 132 |
+
for i, threshold in enumerate(thresholds):
|
| 133 |
+
if normalized_score >= threshold:
|
| 134 |
+
return RATING_SCALE - i
|
| 135 |
+
return 1
|
| 136 |
+
elif rule_type == "lower_better":
|
| 137 |
+
for i, threshold in enumerate(thresholds):
|
| 138 |
+
if normalized_score <= threshold:
|
| 139 |
+
return RATING_SCALE - i
|
| 140 |
+
return 1
|
| 141 |
+
elif rule_type == "target_based":
|
| 142 |
+
target = rule["target"]
|
| 143 |
+
distance = abs(normalized_score - target)
|
| 144 |
+
for i, threshold in enumerate(thresholds):
|
| 145 |
+
if distance <= threshold:
|
| 146 |
+
return RATING_SCALE - i
|
| 147 |
+
return 1
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def normalize_score(score, metric_key):
|
| 152 |
+
if score is None or not isinstance(score, (int, float)):
|
| 153 |
+
return None
|
| 154 |
+
canonical_key = METRIC_ALIASES.get(metric_key, metric_key)
|
| 155 |
+
if canonical_key not in METRIC_RANGES:
|
| 156 |
+
return score
|
| 157 |
+
min_val, max_val = METRIC_RANGES[canonical_key]["min"], METRIC_RANGES[canonical_key]["max"]
|
| 158 |
+
normalized = (score - min_val) / (max_val - min_val)
|
| 159 |
+
return max(0.0, min(1.0, normalized))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def is_valid_metric(metric_key, is_long):
|
| 163 |
+
canonical_key = METRIC_ALIASES.get(metric_key, metric_key)
|
| 164 |
+
rules = SCORING_RULES_LONG if is_long else SCORING_RULES_SHORT
|
| 165 |
+
return canonical_key in rules
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def merge_results(input_dir, output_path=None, is_long=False):
|
| 169 |
+
result_files = [f for f in os.listdir(input_dir) if f.endswith("_results.json")]
|
| 170 |
+
if not result_files:
|
| 171 |
+
return None, None
|
| 172 |
+
|
| 173 |
+
merged = {
|
| 174 |
+
"rating_scale": RATING_SCALE,
|
| 175 |
+
"summary": {"non_drifting": {}, "drifting": {}},
|
| 176 |
+
"per_video": {},
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
for result_file in sorted(result_files):
|
| 180 |
+
metric_key = result_file.replace("_results.json", "")
|
| 181 |
+
if not is_valid_metric(metric_key, is_long):
|
| 182 |
+
continue
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
with open(os.path.join(input_dir, result_file), "r") as f:
|
| 186 |
+
data = json.load(f)
|
| 187 |
+
|
| 188 |
+
score = data.get("average_score") or data.get("average_drift_score")
|
| 189 |
+
norm_score = normalize_score(score, metric_key)
|
| 190 |
+
rating = convert_to_rating(norm_score, metric_key, is_long)
|
| 191 |
+
|
| 192 |
+
metric_summary = {
|
| 193 |
+
"name": metric_key.replace("_", " ").title(),
|
| 194 |
+
"raw_score": score,
|
| 195 |
+
"normalized_score": norm_score,
|
| 196 |
+
"rating": rating,
|
| 197 |
+
"num_videos": data.get("num_videos", 0),
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
if metric_key.startswith("drifting_"):
|
| 201 |
+
merged["summary"]["drifting"][metric_key] = metric_summary
|
| 202 |
+
else:
|
| 203 |
+
merged["summary"]["non_drifting"][metric_key] = metric_summary
|
| 204 |
+
|
| 205 |
+
except Exception as e:
|
| 206 |
+
print(f" Error loading {result_file}: {e}")
|
| 207 |
+
|
| 208 |
+
total_weighted = calculate_weighted_rating(merged["summary"], is_long)
|
| 209 |
+
merged["summary"]["total_weighted_rating"] = total_weighted
|
| 210 |
+
print(f"\n>>> FINAL WEIGHTED RATING: {total_weighted}\n")
|
| 211 |
+
|
| 212 |
+
if output_path is None:
|
| 213 |
+
output_path = os.path.join(input_dir, "merged_results.json")
|
| 214 |
+
with open(output_path, "w") as f:
|
| 215 |
+
json.dump(merged, f, indent=2)
|
| 216 |
+
|
| 217 |
+
return merged, output_path
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def main(args):
|
| 221 |
+
merge_results(args.input_dir, args.output_path, args.is_long)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
parser = argparse.ArgumentParser()
|
| 226 |
+
parser.add_argument("--input_dir", type=str, default="playground/results/toy-video")
|
| 227 |
+
parser.add_argument("--output_path", type=str, default=None)
|
| 228 |
+
parser.add_argument("--is_long", action="store_true")
|
| 229 |
+
args = parser.parse_args()
|
| 230 |
+
main(args)
|
Helios/eval/README.md
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# <u>Evaluation Pipeline</u> by *Helios*
|
| 2 |
+
This repository shows how to evaluate custom models described in the [Helios](https://arxiv.org/abs/2603.04379) paper.
|
| 3 |
+
|
| 4 |
+
## 🎉 Overview
|
| 5 |
+
|
| 6 |
+
### Basic Metrics
|
| 7 |
+
Measuring the basic quality of videos.
|
| 8 |
+
|
| 9 |
+
| Metric | Description | Method |
|
| 10 |
+
|--------|-------------|-------|
|
| 11 |
+
| **Aesthetic** | Aesthetic quality score | CLIP + LAION Aesthetic |
|
| 12 |
+
| **Motion Amplitude** | Motion dynamics degree | Farneback |
|
| 13 |
+
| **Motion Smoothness** | Temporal motion smoothness | AMT |
|
| 14 |
+
| **Semantic** | Overall semantic consistency | ViCLIP |
|
| 15 |
+
| **Naturalness** | Overall semantic consistency | GPT-5.2-2025-12-11 |
|
| 16 |
+
|
| 17 |
+
### Drifting Metrics
|
| 18 |
+
Measuring start-end quality contrast to detect temporal drifting:
|
| 19 |
+
|
| 20 |
+
$$\Delta M_{drift}(V) = |M(V_{start}) - M(V_{end})|$$
|
| 21 |
+
|
| 22 |
+
Where $V_{start}$ is the first 15% of frames and $V_{end}$ is the last 15% of frames.
|
| 23 |
+
|
| 24 |
+
| Metric | Description |
|
| 25 |
+
|--------|-------------|
|
| 26 |
+
| **Drifting Aesthetic** | Aesthetic drifting |
|
| 27 |
+
| **Drifting Motion Smoothness** | Motion smoothness drifting |
|
| 28 |
+
| **Drifting Semantic** | Semantic consistency drifting |
|
| 29 |
+
| **Drifting Naturalness** | Naturalness drifting |
|
| 30 |
+
|
| 31 |
+
### Throughput Metrics
|
| 32 |
+
Measureing the end-to-end performance at a resolution of 384 × 640 under default frame lengths. The reported results include the latency of both the VAE and the text encoder. We should enable all acceleration techniques officially adopted by each model—such as FlashAttention, torch compile,
|
| 33 |
+
KV-cache, and warm-up—to achieve optimal throughput.
|
| 34 |
+
|
| 35 |
+
| Metric | Description |
|
| 36 |
+
|--------|-------------|
|
| 37 |
+
| **Throughput (FPS)** | Inference speed |
|
| 38 |
+
| **Throughput Score** | Inference speed |
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
## ⚙️ Requirements and Installation
|
| 42 |
+
|
| 43 |
+
### Prepare Environment
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
# Activate conda environment
|
| 47 |
+
conda activate helios
|
| 48 |
+
|
| 49 |
+
# Install additional dependencies
|
| 50 |
+
pip install -r requirements.txt
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
### Prepare Ckpts
|
| 54 |
+
```bash
|
| 55 |
+
# Option 1: via script
|
| 56 |
+
cd checkpoints/ && bash get_checkpoints.sh
|
| 57 |
+
|
| 58 |
+
# Option 2: via Hugging Face CLI
|
| 59 |
+
hf download BestWishYsh/HeliosBench-Weights --local-dir ./
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Once ready, the weights will be organized in this format:
|
| 63 |
+
|
| 64 |
+
```
|
| 65 |
+
📦 checkpoints/
|
| 66 |
+
├── 📂 aesthetic_model/
|
| 67 |
+
│ ├── 📄 sa_0_4_vit_l_14_linear.pth
|
| 68 |
+
│ └── 📄 ViT-L-14.pt
|
| 69 |
+
└── 📂 ViCLIP/
|
| 70 |
+
├── 📄 bpe_simple_vocab_16e6.txt.gz
|
| 71 |
+
└── 📄 ViClip-InternVid-10M-FLT.pth
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
## 🗝️ Usage
|
| 76 |
+
|
| 77 |
+
### Prepare Your Videos
|
| 78 |
+
|
| 79 |
+
```
|
| 80 |
+
📦 model_name/
|
| 81 |
+
├── 📄 1_*_ori*.mp4
|
| 82 |
+
├── 📄 2_*_ori*.mp4
|
| 83 |
+
├── ...
|
| 84 |
+
└── 📄 {id}_{target-duration}_{true-duration}.mp4
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
### Run Metrics:
|
| 88 |
+
|
| 89 |
+
```bash
|
| 90 |
+
# Option 1: Run all metrics (recommended)
|
| 91 |
+
bash run_metrics.sh # for single GPU
|
| 92 |
+
bash run_metrics_ddp.sh # for multi-GPU
|
| 93 |
+
|
| 94 |
+
# Option 2: Run individual scripts (same results)
|
| 95 |
+
python 0_get_aesthetic.py
|
| 96 |
+
python 1_get_motion_amplitude.py
|
| 97 |
+
python 2_get_motion_smoothness.py
|
| 98 |
+
python 3_get_semantic.py
|
| 99 |
+
python 4_get_naturalness.py
|
| 100 |
+
|
| 101 |
+
python 5_get_drifting_aesthetic.py
|
| 102 |
+
python 6_get_drifting_motion_smoothness.py
|
| 103 |
+
python 7_get_drifting_semantic.py
|
| 104 |
+
python 8_get_drifting_naturalness.py
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
## Output
|
| 108 |
+
|
| 109 |
+
Results are saved as JSON files in the `playground/results` directory:
|
| 110 |
+
|
| 111 |
+
```bash
|
| 112 |
+
# Convert raw metrics to rating and merge them into one json
|
| 113 |
+
python 9_merge_all_scores.py
|
| 114 |
+
python 10_merge_all_results.py
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
A merged summary is saved to `playground/results/merged_results.json`.
|
| 118 |
+
|
| 119 |
+
```json
|
| 120 |
+
{
|
| 121 |
+
"num_models": 1,
|
| 122 |
+
"score_type": "rating",
|
| 123 |
+
"metrics": [
|
| 124 |
+
"aesthetic",
|
| 125 |
+
"drifting_aesthetic",
|
| 126 |
+
"drifting_motion_smoothness",
|
| 127 |
+
"drifting_naturalness",
|
| 128 |
+
"drifting_semantic",
|
| 129 |
+
"motion_amplitude",
|
| 130 |
+
"motion_smoothness",
|
| 131 |
+
"naturalness",
|
| 132 |
+
"semantic",
|
| 133 |
+
"total_weighted_rating"
|
| 134 |
+
],
|
| 135 |
+
"models": {
|
| 136 |
+
"toy-video": {
|
| 137 |
+
"aesthetic": 9,
|
| 138 |
+
"motion_amplitude": 3,
|
| 139 |
+
"motion_smoothness": 10,
|
| 140 |
+
"naturalness": 7,
|
| 141 |
+
"semantic": 8,
|
| 142 |
+
"drifting_aesthetic": 8,
|
| 143 |
+
"drifting_motion_smoothness": 10,
|
| 144 |
+
"drifting_naturalness": 10,
|
| 145 |
+
"drifting_semantic": 10,
|
| 146 |
+
"total_weighted_rating": 8.247
|
| 147 |
+
}
|
| 148 |
+
},
|
| 149 |
+
"rating_scale": 10
|
| 150 |
+
}
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
For the **Throughput Score**, you should first measure the end-to-end throughput (in FPS). The score increases by 1 point for every 3.2 FPS and is clipped to the range $[1, 10]$ like other metrics. Formally,
|
| 154 |
+
|
| 155 |
+
$$
|
| 156 |
+
\text{Throughput Score} =
|
| 157 |
+
\begin{cases}
|
| 158 |
+
1, & \text{if } \text{FPS} \le 3.2, \\
|
| 159 |
+
\left\lceil \dfrac{\text{FPS}}{3.2} \right\rceil, & \text{if } 3.2 < \text{FPS} < 32, \\
|
| 160 |
+
10, & \text{if } \text{FPS} \ge 32.
|
| 161 |
+
\end{cases}
|
| 162 |
+
$$
|
| 163 |
+
|
| 164 |
+
## 🔒 Acknowledgement
|
| 165 |
+
|
| 166 |
+
* This project wouldn't be possible without the following open-sourced repositories: [OpenS2V-Nexus](https://github.com/PKU-YuanGroup/OpenS2V-Nexus), [VBench](https://github.com/Vchitect/VBench), [ChronoMagic-Bench](https://github.com/PKU-YuanGroup/ChronoMagic-Bench), [FramePack](https://github.com/lllyasviel/FramePack).
|
| 167 |
+
* Existing metrics are insufficient for accurately assessing the performance of video generation models. A promising direction is to develop perceptually aligned metrics that better reflect human judgment.
|
Helios/eval/kill.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pkill -9 -f 0_get_aesthetic.py
|
| 2 |
+
pkill -9 -f 1_get_motion_amplitude.py
|
| 3 |
+
pkill -9 -f 2_get_motion_smoothness.py
|
| 4 |
+
pkill -9 -f 3_get_semantic.py
|
| 5 |
+
pkill -9 -f 4_get_naturalness.py
|
| 6 |
+
|
| 7 |
+
pkill -9 -f 0_get_drifting_aesthetic.py
|
| 8 |
+
pkill -9 -f 1_get_drifting_motion_smoothness.py
|
| 9 |
+
pkill -9 -f 2_get_drifting_semantic.py
|
| 10 |
+
pkill -9 -f 3_get_drifting_naturalness.py
|
| 11 |
+
|
| 12 |
+
pkill -9 -f run_metrics.sh
|
| 13 |
+
pkill -9 -f run_metrics_ddp.sh
|
Helios/eval/requirements.txt
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.7.1
|
| 2 |
+
torchvision==0.22.1
|
| 3 |
+
torchaudio==2.7.1
|
| 4 |
+
triton==3.3.1
|
| 5 |
+
# diffusers==0.36.0
|
| 6 |
+
# transformers==4.57.6
|
| 7 |
+
# sentence-transformers==5.2.3
|
| 8 |
+
git+https://github.com/SHYuanBest/diffusers.git@test
|
| 9 |
+
git+https://github.com/huggingface/transformers.git
|
| 10 |
+
git+https://github.com/huggingface/sentence-transformers.git
|
| 11 |
+
accelerate==1.12.0
|
| 12 |
+
deepspeed==0.18.4
|
| 13 |
+
peft==0.18.1
|
| 14 |
+
huggingface-hub==1.4.1
|
| 15 |
+
zstandard==0.25.0
|
| 16 |
+
wandb==0.23.0
|
| 17 |
+
video-reader-rs==0.4.1
|
| 18 |
+
numpy<2.0.0
|
| 19 |
+
pandas
|
| 20 |
+
pillow
|
| 21 |
+
tqdm
|
| 22 |
+
scipy
|
| 23 |
+
opencv-python
|
| 24 |
+
scikit-image
|
| 25 |
+
ffmpeg-python
|
| 26 |
+
video-reader-rs
|
| 27 |
+
openai-clip
|
| 28 |
+
pyiqa
|
| 29 |
+
timm>=0.9
|
| 30 |
+
omegaconf
|
| 31 |
+
easydict
|
Helios/eval/run_metrics.sh
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
INPUT_CSV="playground/helios_t2v_prompts.csv"
|
| 2 |
+
BASE_OUTPUT_DIR="playground/results"
|
| 3 |
+
PLAYGROUND_DIR="playground"
|
| 4 |
+
|
| 5 |
+
SCORE_TYPE="rating" # ["raw", "normalized", "rating"]
|
| 6 |
+
|
| 7 |
+
NUM_WORKERS=32
|
| 8 |
+
API_KEY=""
|
| 9 |
+
BASE_URL=""
|
| 10 |
+
|
| 11 |
+
GPU_ID=0
|
| 12 |
+
|
| 13 |
+
for MODEL_DIR in "$PLAYGROUND_DIR"/*/ ; do
|
| 14 |
+
MODEL_NAME=$(basename "$MODEL_DIR")
|
| 15 |
+
OUTPUT_DIR="$BASE_OUTPUT_DIR/$MODEL_NAME"
|
| 16 |
+
|
| 17 |
+
if [ ! -d "$MODEL_DIR" ]; then
|
| 18 |
+
continue
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
echo "Processing model: $MODEL_NAME"
|
| 22 |
+
VIDEO_DIR="$MODEL_DIR"
|
| 23 |
+
|
| 24 |
+
# Aesthetic
|
| 25 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 0_get_aesthetic.py \
|
| 26 |
+
--input_csv $INPUT_CSV \
|
| 27 |
+
--video_dir $VIDEO_DIR \
|
| 28 |
+
--output_path $OUTPUT_DIR \
|
| 29 |
+
--clip_model_path "checkpoints/aesthetic_model/ViT-L-14.pt" \
|
| 30 |
+
--aesthetic_model_path "checkpoints/aesthetic_model/sa_0_4_vit_l_14_linear.pth" &
|
| 31 |
+
|
| 32 |
+
# Motion Amplitude
|
| 33 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 1_get_motion_amplitude.py \
|
| 34 |
+
--input_csv $INPUT_CSV \
|
| 35 |
+
--video_dir $VIDEO_DIR \
|
| 36 |
+
--output_path $OUTPUT_DIR \
|
| 37 |
+
--num_workers $NUM_WORKERS &
|
| 38 |
+
|
| 39 |
+
# Motion Smoothness
|
| 40 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 2_get_motion_smoothness.py \
|
| 41 |
+
--input_csv $INPUT_CSV \
|
| 42 |
+
--video_dir $VIDEO_DIR \
|
| 43 |
+
--output_path $OUTPUT_DIR \
|
| 44 |
+
--smoothness_model_path "checkpoints/amt_model/amt-s.pth" &
|
| 45 |
+
|
| 46 |
+
# Semantic
|
| 47 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 3_get_semantic.py \
|
| 48 |
+
--input_csv $INPUT_CSV \
|
| 49 |
+
--video_dir $VIDEO_DIR \
|
| 50 |
+
--output_path $OUTPUT_DIR \
|
| 51 |
+
--semantic_model_path "checkpoints/ViCLIP" &
|
| 52 |
+
|
| 53 |
+
# Naturalness
|
| 54 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 4_get_naturalness.py \
|
| 55 |
+
--input_csv $INPUT_CSV \
|
| 56 |
+
--video_dir $VIDEO_DIR \
|
| 57 |
+
--output_path $OUTPUT_DIR \
|
| 58 |
+
--api_key $API_KEY \
|
| 59 |
+
--base_url $BASE_URL \
|
| 60 |
+
--num_workers $NUM_WORKERS &
|
| 61 |
+
|
| 62 |
+
# Drifting Aesthetic
|
| 63 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 5_get_drifting_aesthetic.py \
|
| 64 |
+
--input_csv $INPUT_CSV \
|
| 65 |
+
--video_dir $VIDEO_DIR \
|
| 66 |
+
--output_path $OUTPUT_DIR \
|
| 67 |
+
--clip_model_path "checkpoints/aesthetic_model/ViT-L-14.pt" \
|
| 68 |
+
--aesthetic_model_path "checkpoints/aesthetic_model/sa_0_4_vit_l_14_linear.pth" &
|
| 69 |
+
|
| 70 |
+
# Drifting Motion Smoothness
|
| 71 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 6_get_drifting_motion_smoothness.py \
|
| 72 |
+
--input_csv $INPUT_CSV \
|
| 73 |
+
--video_dir $VIDEO_DIR \
|
| 74 |
+
--output_path $OUTPUT_DIR \
|
| 75 |
+
--smoothness_model_path "checkpoints/amt_model/amt-s.pth" &
|
| 76 |
+
|
| 77 |
+
# Drifting Semantic
|
| 78 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 7_get_drifting_semantic.py \
|
| 79 |
+
--input_csv $INPUT_CSV \
|
| 80 |
+
--video_dir $VIDEO_DIR \
|
| 81 |
+
--output_path $OUTPUT_DIR \
|
| 82 |
+
--semantic_model_path "checkpoints/ViCLIP" &
|
| 83 |
+
|
| 84 |
+
# Drifting Naturalness
|
| 85 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 8_get_drifting_naturalness.py \
|
| 86 |
+
--input_csv $INPUT_CSV \
|
| 87 |
+
--video_dir $VIDEO_DIR \
|
| 88 |
+
--output_path $OUTPUT_DIR \
|
| 89 |
+
--api_key $API_KEY \
|
| 90 |
+
--base_url $BASE_URL \
|
| 91 |
+
--num_workers $NUM_WORKERS &
|
| 92 |
+
|
| 93 |
+
wait
|
| 94 |
+
|
| 95 |
+
# Merge All Scores
|
| 96 |
+
python 9_merge_all_scores.py \
|
| 97 |
+
--input_dir "$OUTPUT_DIR" \
|
| 98 |
+
--is_long
|
| 99 |
+
done
|
| 100 |
+
|
| 101 |
+
# Merge All Results
|
| 102 |
+
python 10_merge_all_results.py \
|
| 103 |
+
--input_dir "$BASE_OUTPUT_DIR" \
|
| 104 |
+
--score_type "$SCORE_TYPE"
|
Helios/eval/run_metrics_ddp.sh
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
INPUT_CSV="playground/helios_t2v_prompts.csv"
|
| 2 |
+
BASE_OUTPUT_DIR="playground/results"
|
| 3 |
+
PLAYGROUND_DIR="playground"
|
| 4 |
+
|
| 5 |
+
SCORE_TYPE="rating" # ["raw", "normalized", "rating"]
|
| 6 |
+
|
| 7 |
+
NUM_WORKERS=32
|
| 8 |
+
API_KEY=""
|
| 9 |
+
BASE_URL=""
|
| 10 |
+
|
| 11 |
+
NUM_MACHINES=${ARNOLD_WORKER_NUM:-1}
|
| 12 |
+
NUM_PROCESSES_PER_MACHINE=${ARNOLD_WORKER_GPU:-$(nvidia-smi --list-gpus | wc -l)}
|
| 13 |
+
TOTAL_GPUS=$((NUM_MACHINES * NUM_PROCESSES_PER_MACHINE))
|
| 14 |
+
|
| 15 |
+
echo "Detected configuration:"
|
| 16 |
+
echo " Number of machines: $NUM_MACHINES"
|
| 17 |
+
echo " GPUs per machine: $NUM_PROCESSES_PER_MACHINE"
|
| 18 |
+
echo " Total GPUs: $TOTAL_GPUS"
|
| 19 |
+
|
| 20 |
+
MODEL_DIRS=()
|
| 21 |
+
for MODEL_DIR in "$PLAYGROUND_DIR"/*/ ; do
|
| 22 |
+
if [ -d "$MODEL_DIR" ]; then
|
| 23 |
+
MODEL_DIRS+=("$MODEL_DIR")
|
| 24 |
+
fi
|
| 25 |
+
done
|
| 26 |
+
|
| 27 |
+
echo "Found ${#MODEL_DIRS[@]} models to process"
|
| 28 |
+
|
| 29 |
+
process_model() {
|
| 30 |
+
MODEL_DIR=$1
|
| 31 |
+
GPU_ID=$2
|
| 32 |
+
|
| 33 |
+
MODEL_NAME=$(basename "$MODEL_DIR")
|
| 34 |
+
OUTPUT_DIR="$BASE_OUTPUT_DIR/$MODEL_NAME"
|
| 35 |
+
VIDEO_DIR="$MODEL_DIR"
|
| 36 |
+
|
| 37 |
+
echo "Processing model: $MODEL_NAME on GPU $GPU_ID"
|
| 38 |
+
|
| 39 |
+
# Aesthetic
|
| 40 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 0_get_aesthetic.py \
|
| 41 |
+
--input_csv $INPUT_CSV \
|
| 42 |
+
--video_dir $VIDEO_DIR \
|
| 43 |
+
--output_path $OUTPUT_DIR \
|
| 44 |
+
--clip_model_path "checkpoints/aesthetic_model/ViT-L-14.pt" \
|
| 45 |
+
--aesthetic_model_path "checkpoints/aesthetic_model/sa_0_4_vit_l_14_linear.pth" &
|
| 46 |
+
|
| 47 |
+
# Motion Amplitude
|
| 48 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 1_get_motion_amplitude.py \
|
| 49 |
+
--input_csv $INPUT_CSV \
|
| 50 |
+
--video_dir $VIDEO_DIR \
|
| 51 |
+
--output_path $OUTPUT_DIR \
|
| 52 |
+
--num_workers $NUM_WORKERS &
|
| 53 |
+
|
| 54 |
+
# Motion Smoothness
|
| 55 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 2_get_motion_smoothness.py \
|
| 56 |
+
--input_csv $INPUT_CSV \
|
| 57 |
+
--video_dir $VIDEO_DIR \
|
| 58 |
+
--output_path $OUTPUT_DIR \
|
| 59 |
+
--smoothness_model_path "checkpoints/amt_model/amt-s.pth" &
|
| 60 |
+
|
| 61 |
+
# Semantic
|
| 62 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 3_get_semantic.py \
|
| 63 |
+
--input_csv $INPUT_CSV \
|
| 64 |
+
--video_dir $VIDEO_DIR \
|
| 65 |
+
--output_path $OUTPUT_DIR \
|
| 66 |
+
--semantic_model_path "checkpoints/ViCLIP" &
|
| 67 |
+
|
| 68 |
+
# Naturalness
|
| 69 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 4_get_naturalness.py \
|
| 70 |
+
--input_csv $INPUT_CSV \
|
| 71 |
+
--video_dir $VIDEO_DIR \
|
| 72 |
+
--output_path $OUTPUT_DIR \
|
| 73 |
+
--api_key $API_KEY \
|
| 74 |
+
--base_url $BASE_URL \
|
| 75 |
+
--num_workers $NUM_WORKERS &
|
| 76 |
+
|
| 77 |
+
# Drifting Aesthetic
|
| 78 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 5_get_drifting_aesthetic.py \
|
| 79 |
+
--input_csv $INPUT_CSV \
|
| 80 |
+
--video_dir $VIDEO_DIR \
|
| 81 |
+
--output_path $OUTPUT_DIR \
|
| 82 |
+
--clip_model_path "checkpoints/aesthetic_model/ViT-L-14.pt" \
|
| 83 |
+
--aesthetic_model_path "checkpoints/aesthetic_model/sa_0_4_vit_l_14_linear.pth" &
|
| 84 |
+
|
| 85 |
+
# Drifting Motion Smoothness
|
| 86 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 6_get_drifting_motion_smoothness.py \
|
| 87 |
+
--input_csv $INPUT_CSV \
|
| 88 |
+
--video_dir $VIDEO_DIR \
|
| 89 |
+
--output_path $OUTPUT_DIR \
|
| 90 |
+
--smoothness_model_path "checkpoints/amt_model/amt-s.pth" &
|
| 91 |
+
|
| 92 |
+
# Drifting Semantic
|
| 93 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 7_get_drifting_semantic.py \
|
| 94 |
+
--input_csv $INPUT_CSV \
|
| 95 |
+
--video_dir $VIDEO_DIR \
|
| 96 |
+
--output_path $OUTPUT_DIR \
|
| 97 |
+
--semantic_model_path "checkpoints/ViCLIP" &
|
| 98 |
+
|
| 99 |
+
# Drifting Naturalness
|
| 100 |
+
CUDA_VISIBLE_DEVICES=$GPU_ID python 8_get_drifting_naturalness.py \
|
| 101 |
+
--input_csv $INPUT_CSV \
|
| 102 |
+
--video_dir $VIDEO_DIR \
|
| 103 |
+
--output_path $OUTPUT_DIR \
|
| 104 |
+
--api_key $API_KEY \
|
| 105 |
+
--base_url $BASE_URL \
|
| 106 |
+
--num_workers $NUM_WORKERS &
|
| 107 |
+
|
| 108 |
+
wait
|
| 109 |
+
|
| 110 |
+
# Merge All Scores
|
| 111 |
+
python 9_merge_all_scores.py \
|
| 112 |
+
--input_dir "$OUTPUT_DIR" \
|
| 113 |
+
--is_long
|
| 114 |
+
|
| 115 |
+
echo "Finished processing model: $MODEL_NAME on GPU $GPU_ID"
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
idx=0
|
| 119 |
+
for MODEL_DIR in "${MODEL_DIRS[@]}"; do
|
| 120 |
+
LOCAL_GPU_ID=$((idx % NUM_PROCESSES_PER_MACHINE))
|
| 121 |
+
|
| 122 |
+
process_model "$MODEL_DIR" $LOCAL_GPU_ID &
|
| 123 |
+
|
| 124 |
+
idx=$((idx + 1))
|
| 125 |
+
|
| 126 |
+
if [ $((idx % NUM_PROCESSES_PER_MACHINE)) -eq 0 ]; then
|
| 127 |
+
wait -n
|
| 128 |
+
fi
|
| 129 |
+
done
|
| 130 |
+
|
| 131 |
+
wait
|
| 132 |
+
|
| 133 |
+
echo "All models processed!"
|
| 134 |
+
|
| 135 |
+
# Merge All Results
|
| 136 |
+
python 10_merge_all_results.py \
|
| 137 |
+
--input_dir "$BASE_OUTPUT_DIR" \
|
| 138 |
+
--score_type "$SCORE_TYPE"
|
Helios/eval_moviebench/0_get_aesthetic.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import clip
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
from utils.utils import clip_transform, discover_benchmark_videos, enrich_result_record, load_existing_results, load_video
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
BATCH_SIZE = 32
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_aesthetic_model(path_to_model):
|
| 18 |
+
"""Load the aesthetic predictor model"""
|
| 19 |
+
m = nn.Linear(768, 1)
|
| 20 |
+
s = torch.load(path_to_model, map_location="cpu", weights_only=False)
|
| 21 |
+
m.load_state_dict(s)
|
| 22 |
+
m.eval()
|
| 23 |
+
return m
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def evaluate_aesthetic(aesthetic_model, clip_model, video_path, height=384, width=640, device="cuda"):
|
| 27 |
+
"""Evaluate aesthetic quality for a single video"""
|
| 28 |
+
aesthetic_model.eval()
|
| 29 |
+
clip_model.eval()
|
| 30 |
+
|
| 31 |
+
# Load video frames
|
| 32 |
+
images = load_video(video_path, height=height, width=width)
|
| 33 |
+
image_transform = clip_transform(224)
|
| 34 |
+
aesthetic_scores_list = []
|
| 35 |
+
|
| 36 |
+
# Process in batches
|
| 37 |
+
for i in range(0, len(images), BATCH_SIZE):
|
| 38 |
+
image_batch = images[i : i + BATCH_SIZE]
|
| 39 |
+
image_batch = image_transform(image_batch)
|
| 40 |
+
image_batch = image_batch.to(device)
|
| 41 |
+
|
| 42 |
+
with torch.no_grad():
|
| 43 |
+
image_feats = clip_model.encode_image(image_batch).to(torch.float32)
|
| 44 |
+
image_feats = F.normalize(image_feats, dim=-1, p=2)
|
| 45 |
+
aesthetic_scores = aesthetic_model(image_feats).squeeze(dim=-1)
|
| 46 |
+
|
| 47 |
+
aesthetic_scores_list.append(aesthetic_scores)
|
| 48 |
+
|
| 49 |
+
# Combine all scores
|
| 50 |
+
aesthetic_scores = torch.cat(aesthetic_scores_list, dim=0)
|
| 51 |
+
normalized_aesthetic_scores = aesthetic_scores / 10.0
|
| 52 |
+
avg_score = torch.mean(normalized_aesthetic_scores, dim=0, keepdim=True)
|
| 53 |
+
|
| 54 |
+
return avg_score.item()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def main(args):
|
| 58 |
+
baseline_name = os.path.basename(args.video_dir)
|
| 59 |
+
output_path = os.path.join(args.output_path, baseline_name)
|
| 60 |
+
output_json_path = os.path.join(output_path, "aesthetic_results.json")
|
| 61 |
+
|
| 62 |
+
# Set device
|
| 63 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 64 |
+
print(f"Using device: {device}")
|
| 65 |
+
|
| 66 |
+
# Load existing results if available
|
| 67 |
+
existing_results = load_existing_results(output_json_path)
|
| 68 |
+
if existing_results:
|
| 69 |
+
print(f"Found existing results at {output_json_path}, loading...")
|
| 70 |
+
print(f"Loaded {len(existing_results)} existing results")
|
| 71 |
+
|
| 72 |
+
# Get all videos to process
|
| 73 |
+
video_records = discover_benchmark_videos(args.video_dir, args.input_csv)
|
| 74 |
+
print(f"\nFound {len(video_records)} videos in directory")
|
| 75 |
+
|
| 76 |
+
# Check which videos need processing
|
| 77 |
+
results = []
|
| 78 |
+
scores = []
|
| 79 |
+
videos_to_process = []
|
| 80 |
+
|
| 81 |
+
for record in video_records:
|
| 82 |
+
if record["id"] in existing_results:
|
| 83 |
+
results.append(existing_results[record["id"]])
|
| 84 |
+
scores.append(existing_results[record["id"]]["aesthetic_score"])
|
| 85 |
+
else:
|
| 86 |
+
videos_to_process.append(record)
|
| 87 |
+
|
| 88 |
+
print(f"Already processed: {len(existing_results)} videos")
|
| 89 |
+
print(f"Need to process: {len(videos_to_process)} videos")
|
| 90 |
+
|
| 91 |
+
# Process remaining videos
|
| 92 |
+
if videos_to_process:
|
| 93 |
+
# Load models
|
| 94 |
+
print("Loading CLIP model...")
|
| 95 |
+
clip_model, preprocess = clip.load(args.clip_model_path, device=device)
|
| 96 |
+
|
| 97 |
+
print("Loading aesthetic predictor model...")
|
| 98 |
+
aesthetic_model = get_aesthetic_model(args.aesthetic_model_path).to(device)
|
| 99 |
+
|
| 100 |
+
print("\nEvaluating remaining videos...")
|
| 101 |
+
for record in tqdm(videos_to_process):
|
| 102 |
+
try:
|
| 103 |
+
score = evaluate_aesthetic(
|
| 104 |
+
aesthetic_model,
|
| 105 |
+
clip_model,
|
| 106 |
+
record["video_path"],
|
| 107 |
+
height=args.height,
|
| 108 |
+
width=args.width,
|
| 109 |
+
device=device,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
result_item = enrich_result_record(record, aesthetic_score=score)
|
| 113 |
+
results.append(result_item)
|
| 114 |
+
scores.append(score)
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
print(f"Error processing {record['video_name']}: {str(e)}")
|
| 118 |
+
continue
|
| 119 |
+
else:
|
| 120 |
+
print("No videos to process. Skipping evaluation.")
|
| 121 |
+
return
|
| 122 |
+
|
| 123 |
+
# Calculate overall metrics
|
| 124 |
+
if scores:
|
| 125 |
+
avg_score = sum(scores) / len(scores)
|
| 126 |
+
|
| 127 |
+
# Sort results by video_id
|
| 128 |
+
results_sorted = sorted(results, key=lambda x: x["id"])
|
| 129 |
+
|
| 130 |
+
output = {
|
| 131 |
+
"metric": "aesthetic",
|
| 132 |
+
"average_score": avg_score,
|
| 133 |
+
"num_videos": len(scores),
|
| 134 |
+
"per_video_results": results_sorted,
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
# Save results
|
| 138 |
+
os.makedirs(output_path, exist_ok=True)
|
| 139 |
+
with open(output_json_path, "w") as f:
|
| 140 |
+
json.dump(output, f, indent=2)
|
| 141 |
+
|
| 142 |
+
print(f"\n{'=' * 60}")
|
| 143 |
+
print("Results Summary:")
|
| 144 |
+
print(f"{'=' * 60}")
|
| 145 |
+
print(f"Average Aesthetic Score: {avg_score:.4f}")
|
| 146 |
+
print(f"Number of videos evaluated: {len(scores)}")
|
| 147 |
+
print(f"Results saved to: {output_json_path}")
|
| 148 |
+
print(f"{'=' * 60}\n")
|
| 149 |
+
else:
|
| 150 |
+
print("No videos were successfully evaluated!")
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
parser = argparse.ArgumentParser(description="Evaluate video aesthetic using CLIP + LAION aesthetic predictor")
|
| 155 |
+
|
| 156 |
+
# Input/Output arguments
|
| 157 |
+
parser.add_argument("--height", type=int, default=384)
|
| 158 |
+
parser.add_argument("--width", type=int, default=640)
|
| 159 |
+
parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
|
| 160 |
+
parser.add_argument("--video_dir", type=str, default="playground/toy-video")
|
| 161 |
+
parser.add_argument("--output_path", type=str, default="playground/results")
|
| 162 |
+
|
| 163 |
+
# Model arguments
|
| 164 |
+
parser.add_argument("--clip_model_path", type=str, default="checkpoints/aesthetic_model/ViT-L-14.pt")
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--aesthetic_model_path", type=str, default="checkpoints/aesthetic_model/sa_0_4_vit_l_14_linear.pth"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
args = parser.parse_args()
|
| 170 |
+
|
| 171 |
+
main(args)
|