maomao517 commited on
Commit
d10d213
·
verified ·
1 Parent(s): a6866af

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +9 -0
  2. .gitignore +10 -0
  3. LICENCE.txt +407 -0
  4. README.md +179 -8
  5. assets/LBM.jpg +3 -0
  6. assets/depth_normal.jpg +3 -0
  7. assets/object_removal.jpg +3 -0
  8. assets/relight.gif +3 -0
  9. assets/relight.jpg +3 -0
  10. assets/relight_2.gif +3 -0
  11. assets/shadow_control.gif +3 -0
  12. assets/upscaler.jpg +3 -0
  13. examples/inference/gradio_demo.py +234 -0
  14. examples/inference/inference.py +59 -0
  15. examples/inference/utils.py +41 -0
  16. examples/training/config/surface.yaml +31 -0
  17. examples/training/train_lbm_surface.py +546 -0
  18. frpc_linux_amd64_v0.3 +3 -0
  19. img/input_img/1.jpg +0 -0
  20. img/output_img/output_image.jpg +0 -0
  21. img/output_img/source_image.jpg +0 -0
  22. pyproject.toml +39 -0
  23. requirements.txt +24 -0
  24. src/lbm/config.py +141 -0
  25. src/lbm/data/__init__.py +62 -0
  26. src/lbm/data/datasets/__init__.py +9 -0
  27. src/lbm/data/datasets/collation_fn.py +41 -0
  28. src/lbm/data/datasets/dataset.py +243 -0
  29. src/lbm/data/datasets/datasets_config.py +42 -0
  30. src/lbm/data/filters/__init__.py +12 -0
  31. src/lbm/data/filters/base.py +21 -0
  32. src/lbm/data/filters/filter_wrapper.py +36 -0
  33. src/lbm/data/filters/filters.py +33 -0
  34. src/lbm/data/filters/filters_config.py +32 -0
  35. src/lbm/data/mappers/__init__.py +19 -0
  36. src/lbm/data/mappers/base.py +26 -0
  37. src/lbm/data/mappers/mappers.py +135 -0
  38. src/lbm/data/mappers/mappers_config.py +109 -0
  39. src/lbm/data/mappers/mappers_wrapper.py +31 -0
  40. src/lbm/inference/__init__.py +4 -0
  41. src/lbm/inference/inference.py +70 -0
  42. src/lbm/inference/utils.py +222 -0
  43. src/lbm/models/__init__.py +0 -0
  44. src/lbm/models/base/__init__.py +4 -0
  45. src/lbm/models/base/base_model.py +66 -0
  46. src/lbm/models/base/model_config.py +8 -0
  47. src/lbm/models/embedders/__init__.py +4 -0
  48. src/lbm/models/embedders/base/__init__.py +4 -0
  49. src/lbm/models/embedders/base/base_conditioner.py +60 -0
  50. src/lbm/models/embedders/base/base_conditioner_config.py +27 -0
.gitattributes CHANGED
@@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/LBM.jpg filter=lfs diff=lfs merge=lfs -text
37
+ assets/depth_normal.jpg filter=lfs diff=lfs merge=lfs -text
38
+ assets/object_removal.jpg filter=lfs diff=lfs merge=lfs -text
39
+ assets/relight.gif filter=lfs diff=lfs merge=lfs -text
40
+ assets/relight.jpg filter=lfs diff=lfs merge=lfs -text
41
+ assets/relight_2.gif filter=lfs diff=lfs merge=lfs -text
42
+ assets/shadow_control.gif filter=lfs diff=lfs merge=lfs -text
43
+ assets/upscaler.jpg filter=lfs diff=lfs merge=lfs -text
44
+ frpc_linux_amd64_v0.3 filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ *.ipynb
2
+ *.png
3
+ *.pyc
4
+ *.gradio
5
+ *.safetensors
6
+ examples/inference/ckpts/*
7
+ examples/inference/examples/*
8
+ envs/*
9
+ checkpoints/*
10
+ *.sh
LICENCE.txt ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution-NonCommercial 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution-NonCommercial 4.0 International Public
58
+ License
59
+
60
+ By exercising the Licensed Rights (defined below), You accept and agree
61
+ to be bound by the terms and conditions of this Creative Commons
62
+ Attribution-NonCommercial 4.0 International Public License ("Public
63
+ License"). To the extent this Public License may be interpreted as a
64
+ contract, You are granted the Licensed Rights in consideration of Your
65
+ acceptance of these terms and conditions, and the Licensor grants You
66
+ such rights in consideration of benefits the Licensor receives from
67
+ making the Licensed Material available under these terms and
68
+ conditions.
69
+
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. Copyright and Similar Rights means copyright and/or similar rights
88
+ closely related to copyright including, without limitation,
89
+ performance, broadcast, sound recording, and Sui Generis Database
90
+ Rights, without regard to how the rights are labeled or
91
+ categorized. For purposes of this Public License, the rights
92
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
93
+ Rights.
94
+ d. Effective Technological Measures means those measures that, in the
95
+ absence of proper authority, may not be circumvented under laws
96
+ fulfilling obligations under Article 11 of the WIPO Copyright
97
+ Treaty adopted on December 20, 1996, and/or similar international
98
+ agreements.
99
+
100
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
101
+ any other exception or limitation to Copyright and Similar Rights
102
+ that applies to Your use of the Licensed Material.
103
+
104
+ f. Licensed Material means the artistic or literary work, database,
105
+ or other material to which the Licensor applied this Public
106
+ License.
107
+
108
+ g. Licensed Rights means the rights granted to You subject to the
109
+ terms and conditions of this Public License, which are limited to
110
+ all Copyright and Similar Rights that apply to Your use of the
111
+ Licensed Material and that the Licensor has authority to license.
112
+
113
+ h. Licensor means the individual(s) or entity(ies) granting rights
114
+ under this Public License.
115
+
116
+ i. NonCommercial means not primarily intended for or directed towards
117
+ commercial advantage or monetary compensation. For purposes of
118
+ this Public License, the exchange of the Licensed Material for
119
+ other material subject to Copyright and Similar Rights by digital
120
+ file-sharing or similar means is NonCommercial provided there is
121
+ no payment of monetary compensation in connection with the
122
+ exchange.
123
+
124
+ j. Share means to provide material to the public by any means or
125
+ process that requires permission under the Licensed Rights, such
126
+ as reproduction, public display, public performance, distribution,
127
+ dissemination, communication, or importation, and to make material
128
+ available to the public including in ways that members of the
129
+ public may access the material from a place and at a time
130
+ individually chosen by them.
131
+
132
+ k. Sui Generis Database Rights means rights other than copyright
133
+ resulting from Directive 96/9/EC of the European Parliament and of
134
+ the Council of 11 March 1996 on the legal protection of databases,
135
+ as amended and/or succeeded, as well as other essentially
136
+ equivalent rights anywhere in the world.
137
+
138
+ l. You means the individual or entity exercising the Licensed Rights
139
+ under this Public License. Your has a corresponding meaning.
140
+
141
+
142
+ Section 2 -- Scope.
143
+
144
+ a. License grant.
145
+
146
+ 1. Subject to the terms and conditions of this Public License,
147
+ the Licensor hereby grants You a worldwide, royalty-free,
148
+ non-sublicensable, non-exclusive, irrevocable license to
149
+ exercise the Licensed Rights in the Licensed Material to:
150
+
151
+ a. reproduce and Share the Licensed Material, in whole or
152
+ in part, for NonCommercial purposes only; and
153
+
154
+ b. produce, reproduce, and Share Adapted Material for
155
+ NonCommercial purposes only.
156
+
157
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
158
+ Exceptions and Limitations apply to Your use, this Public
159
+ License does not apply, and You do not need to comply with
160
+ its terms and conditions.
161
+
162
+ 3. Term. The term of this Public License is specified in Section
163
+ 6(a).
164
+
165
+ 4. Media and formats; technical modifications allowed. The
166
+ Licensor authorizes You to exercise the Licensed Rights in
167
+ all media and formats whether now known or hereafter created,
168
+ and to make technical modifications necessary to do so. The
169
+ Licensor waives and/or agrees not to assert any right or
170
+ authority to forbid You from making technical modifications
171
+ necessary to exercise the Licensed Rights, including
172
+ technical modifications necessary to circumvent Effective
173
+ Technological Measures. For purposes of this Public License,
174
+ simply making modifications authorized by this Section 2(a)
175
+ (4) never produces Adapted Material.
176
+
177
+ 5. Downstream recipients.
178
+
179
+ a. Offer from the Licensor -- Licensed Material. Every
180
+ recipient of the Licensed Material automatically
181
+ receives an offer from the Licensor to exercise the
182
+ Licensed Rights under the terms and conditions of this
183
+ Public License.
184
+
185
+ b. No downstream restrictions. You may not offer or impose
186
+ any additional or different terms or conditions on, or
187
+ apply any Effective Technological Measures to, the
188
+ Licensed Material if doing so restricts exercise of the
189
+ Licensed Rights by any recipient of the Licensed
190
+ Material.
191
+
192
+ 6. No endorsement. Nothing in this Public License constitutes or
193
+ may be construed as permission to assert or imply that You
194
+ are, or that Your use of the Licensed Material is, connected
195
+ with, or sponsored, endorsed, or granted official status by,
196
+ the Licensor or others designated to receive attribution as
197
+ provided in Section 3(a)(1)(A)(i).
198
+
199
+ b. Other rights.
200
+
201
+ 1. Moral rights, such as the right of integrity, are not
202
+ licensed under this Public License, nor are publicity,
203
+ privacy, and/or other similar personality rights; however, to
204
+ the extent possible, the Licensor waives and/or agrees not to
205
+ assert any such rights held by the Licensor to the limited
206
+ extent necessary to allow You to exercise the Licensed
207
+ Rights, but not otherwise.
208
+
209
+ 2. Patent and trademark rights are not licensed under this
210
+ Public License.
211
+
212
+ 3. To the extent possible, the Licensor waives any right to
213
+ collect royalties from You for the exercise of the Licensed
214
+ Rights, whether directly or through a collecting society
215
+ under any voluntary or waivable statutory or compulsory
216
+ licensing scheme. In all other cases the Licensor expressly
217
+ reserves any right to collect such royalties, including when
218
+ the Licensed Material is used other than for NonCommercial
219
+ purposes.
220
+
221
+
222
+ Section 3 -- License Conditions.
223
+
224
+ Your exercise of the Licensed Rights is expressly made subject to the
225
+ following conditions.
226
+
227
+ a. Attribution.
228
+
229
+ 1. If You Share the Licensed Material (including in modified
230
+ form), You must:
231
+
232
+ a. retain the following if it is supplied by the Licensor
233
+ with the Licensed Material:
234
+
235
+ i. identification of the creator(s) of the Licensed
236
+ Material and any others designated to receive
237
+ attribution, in any reasonable manner requested by
238
+ the Licensor (including by pseudonym if
239
+ designated);
240
+
241
+ ii. a copyright notice;
242
+
243
+ iii. a notice that refers to this Public License;
244
+
245
+ iv. a notice that refers to the disclaimer of
246
+ warranties;
247
+
248
+ v. a URI or hyperlink to the Licensed Material to the
249
+ extent reasonably practicable;
250
+
251
+ b. indicate if You modified the Licensed Material and
252
+ retain an indication of any previous modifications; and
253
+
254
+ c. indicate the Licensed Material is licensed under this
255
+ Public License, and include the text of, or the URI or
256
+ hyperlink to, this Public License.
257
+
258
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
259
+ reasonable manner based on the medium, means, and context in
260
+ which You Share the Licensed Material. For example, it may be
261
+ reasonable to satisfy the conditions by providing a URI or
262
+ hyperlink to a resource that includes the required
263
+ information.
264
+
265
+ 3. If requested by the Licensor, You must remove any of the
266
+ information required by Section 3(a)(1)(A) to the extent
267
+ reasonably practicable.
268
+
269
+ 4. If You Share Adapted Material You produce, the Adapter's
270
+ License You apply must not prevent recipients of the Adapted
271
+ Material from complying with this Public License.
272
+
273
+
274
+ Section 4 -- Sui Generis Database Rights.
275
+
276
+ Where the Licensed Rights include Sui Generis Database Rights that
277
+ apply to Your use of the Licensed Material:
278
+
279
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
280
+ to extract, reuse, reproduce, and Share all or a substantial
281
+ portion of the contents of the database for NonCommercial purposes
282
+ only;
283
+
284
+ b. if You include all or a substantial portion of the database
285
+ contents in a database in which You have Sui Generis Database
286
+ Rights, then the database in which You have Sui Generis Database
287
+ Rights (but not its individual contents) is Adapted Material; and
288
+
289
+ c. You must comply with the conditions in Section 3(a) if You Share
290
+ all or a substantial portion of the contents of the database.
291
+
292
+ For the avoidance of doubt, this Section 4 supplements and does not
293
+ replace Your obligations under this Public License where the Licensed
294
+ Rights include other Copyright and Similar Rights.
295
+
296
+
297
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
298
+
299
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
300
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
301
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
302
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
303
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
304
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
305
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
306
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
307
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
308
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
309
+
310
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
311
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
312
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
313
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
314
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
315
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
316
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
317
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
318
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
319
+
320
+ c. The disclaimer of warranties and limitation of liability provided
321
+ above shall be interpreted in a manner that, to the extent
322
+ possible, most closely approximates an absolute disclaimer and
323
+ waiver of all liability.
324
+
325
+
326
+ Section 6 -- Term and Termination.
327
+
328
+ a. This Public License applies for the term of the Copyright and
329
+ Similar Rights licensed here. However, if You fail to comply with
330
+ this Public License, then Your rights under this Public License
331
+ terminate automatically.
332
+
333
+ b. Where Your right to use the Licensed Material has terminated under
334
+ Section 6(a), it reinstates:
335
+
336
+ 1. automatically as of the date the violation is cured, provided
337
+ it is cured within 30 days of Your discovery of the
338
+ violation; or
339
+
340
+ 2. upon express reinstatement by the Licensor.
341
+
342
+ For the avoidance of doubt, this Section 6(b) does not affect any
343
+ right the Licensor may have to seek remedies for Your violations
344
+ of this Public License.
345
+
346
+ c. For the avoidance of doubt, the Licensor may also offer the
347
+ Licensed Material under separate terms or conditions or stop
348
+ distributing the Licensed Material at any time; however, doing so
349
+ will not terminate this Public License.
350
+
351
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
352
+ License.
353
+
354
+
355
+ Section 7 -- Other Terms and Conditions.
356
+
357
+ a. The Licensor shall not be bound by any additional or different
358
+ terms or conditions communicated by You unless expressly agreed.
359
+
360
+ b. Any arrangements, understandings, or agreements regarding the
361
+ Licensed Material not stated herein are separate from and
362
+ independent of the terms and conditions of this Public License.
363
+
364
+
365
+ Section 8 -- Interpretation.
366
+
367
+ a. For the avoidance of doubt, this Public License does not, and
368
+ shall not be interpreted to, reduce, limit, restrict, or impose
369
+ conditions on any use of the Licensed Material that could lawfully
370
+ be made without permission under this Public License.
371
+
372
+ b. To the extent possible, if any provision of this Public License is
373
+ deemed unenforceable, it shall be automatically reformed to the
374
+ minimum extent necessary to make it enforceable. If the provision
375
+ cannot be reformed, it shall be severed from this Public License
376
+ without affecting the enforceability of the remaining terms and
377
+ conditions.
378
+
379
+ c. No term or condition of this Public License will be waived and no
380
+ failure to comply consented to unless expressly agreed to by the
381
+ Licensor.
382
+
383
+ d. Nothing in this Public License constitutes or may be interpreted
384
+ as a limitation upon, or waiver of, any privileges and immunities
385
+ that apply to the Licensor or You, including from the legal
386
+ processes of any jurisdiction or authority.
387
+
388
+ =======================================================================
389
+
390
+ Creative Commons is not a party to its public
391
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
392
+ its public licenses to material it publishes and in those instances
393
+ will be considered the “Licensor.” The text of the Creative Commons
394
+ public licenses is dedicated to the public domain under the CC0 Public
395
+ Domain Dedication. Except for the limited purpose of indicating that
396
+ material is shared under a Creative Commons public license or as
397
+ otherwise permitted by the Creative Commons policies published at
398
+ creativecommons.org/policies, Creative Commons does not authorize the
399
+ use of the trademark "Creative Commons" or any other trademark or logo
400
+ of Creative Commons without its prior written consent including,
401
+ without limitation, in connection with any unauthorized modifications
402
+ to any of its public licenses or any other arrangements,
403
+ understandings, or agreements concerning use of licensed material. For
404
+ the avoidance of doubt, this paragraph does not form part of the
405
+ public licenses.
406
+
407
+ Creative Commons may be contacted at creativecommons.org.
README.md CHANGED
@@ -1,12 +1,183 @@
1
  ---
2
- title: Homeoppoer.cachehuggingfacegradiofrpc
3
- emoji: 📉
4
- colorFrom: indigo
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 5.35.0
8
- app_file: app.py
9
- pinned: false
10
  ---
 
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: homeoppoer.cachehuggingfacegradiofrpc
3
+ app_file: frpc_linux_amd64_v0.3
 
 
4
  sdk: gradio
5
+ sdk_version: 5.29.0
 
 
6
  ---
7
+ # Latent Bridge Matching (LBM)
8
 
9
+ This repository is the official implementation of the paper [LBM: Latent Bridge Matching for Fast Image-to-Image Translation](http://arxiv.org/abs/2503.07535).
10
+
11
+ <p align="center">
12
+ <a href="https://arxiv.org/abs/2503.07535">
13
+ <img src='https://img.shields.io/badge/Paper-2503.07535-green' />
14
+ </a>
15
+ <a href="https://gojasper.github.io/latent-bridge-matching/">
16
+ <img src='https://img.shields.io/badge/Project-page-blue' />
17
+ </a>
18
+ <a href='https://creativecommons.org/licenses/by-nd/4.0/legalcode'>
19
+ <img src="https://img.shields.io/badge/Licence-CC.BY.NC-purple" />
20
+ </a>
21
+ <a href="https://huggingface.co/spaces/jasperai/LBM_relighting">
22
+ <img src='https://img.shields.io/badge/%F0%9F%A4%97%20Demo-Object%20Relighting-orange' />
23
+ </a>
24
+ <br>
25
+ </a>
26
+ <a href="https://huggingface.co/jasperai/LBM_relighting">
27
+ <img src='https://img.shields.io/badge/%F0%9F%A4%97%20Ckpt-Object%20Relighting-yellow' />
28
+ </a>
29
+ <a href="https://huggingface.co/jasperai/LBM_normals">
30
+ <img src='https://img.shields.io/badge/%F0%9F%A4%97%20Ckpt-Normals-yellow' />
31
+ </a>
32
+ <a href="https://huggingface.co/jasperai/LBM_depth">
33
+ <img src='https://img.shields.io/badge/%F0%9F%A4%97%20Ckpt-Depth-yellow' />
34
+ </a>
35
+ <p align="center">
36
+ <img src="assets/relight.jpg" alt="LBM Teaser" width="800"/>
37
+ </p>
38
+
39
+
40
+ <!-- link to the demo with link big button -->
41
+ <p align="center">
42
+ <a href="https://huggingface.co/spaces/jasperai/LBM_relighting">
43
+ <b style="font-size: 20px;">DEMO space</b>
44
+ </a>
45
+ </p>
46
+
47
+
48
+ ## Abstract
49
+ In this paper, we introduce Latent Bridge Matching (LBM), a new, versatile and scalable method that relies on Bridge Matching in a latent space to achieve fast image-to-image translation. We show that the method can reach state-of-the-art results for various image-to-image tasks using only a single inference step. In addition to its efficiency, we also demonstrate the versatility of the method across different image translation tasks such as object removal, normal and depth estimation, and object relighting. We also derive a conditional framework of LBM and demonstrate its effectiveness by tackling the tasks of controllable image relighting and shadow generation.
50
+
51
+ <p align="center">
52
+ <img style="width:600px;" src="assets/LBM.jpg">
53
+ </p>
54
+
55
+ ## License
56
+ This code is released under the **Creative Commons BY-NC 4.0 license**.
57
+
58
+ ## Considered Use-cases
59
+ We validate the method on various use-cases such as object relighting, image restoration, object removal, depth and normal maps estimation as well as controllable object relighting and shadow generation.
60
+ <details>
61
+ <summary><b>Image Relighting 🔦</b></summary>
62
+ <p>
63
+ For object relighting, the method should translate the encoded source images created by pasting the foreground onto the target background image to the desired target relighted image.
64
+ </p>
65
+ <p align="center">
66
+ <img style="width:600px;" src="assets/relight.jpg">
67
+ </p>
68
+ </details>
69
+ <details>
70
+ <summary><b>Image Restoration 🧹 </b></summary>
71
+ <p>
72
+ In the context of image restoration, the method shall transport the distribution of the degraded images to the distribution of the clean images.
73
+ </p>
74
+ <p align="center">
75
+ <img style="width:600px;" src="assets/upscaler.jpg">
76
+ </p>
77
+ </details>
78
+ <details>
79
+ <summary><b>Object Removal ✂️</b></summary>
80
+ For object removal, the model is trained to find a transport map from the masked images to the images without the objects
81
+ <p align="center">
82
+ <img style="width:600px;" src="assets/object_removal.jpg">
83
+ </p>
84
+ </details>
85
+ <details>
86
+ <summary><b>Controllable Image Relighting and Shadow Generation🕹️</b></summary>
87
+ <p>
88
+ We also derive a conditional framework of LBM and demonstrate its effectiveness by tackling the tasks of controllable image relighting and shadow generation
89
+ </p>
90
+ <p align="center">
91
+ <img style="width:256px;" src="assets/relight.gif"> <img style="width:256px;" src="assets/shadow_control.gif">
92
+ </p>
93
+ </details>
94
+ <details>
95
+ <summary><b>Normals and Depth Maps Estimation 🗺️</b></summary>
96
+ <p>
97
+ Finally, we also consider common tasks such as normal and depth estimation where the model should translate an input image into a normal or depth map
98
+ </p>
99
+ <p align="center">
100
+ <img style="width:600px;" src="assets/depth_normal.jpg">
101
+ </p>
102
+ </details>
103
+
104
+
105
+
106
+ ## Setup
107
+ To be up and running, you need first to create a virtual env with at least python3.10 installed and activate it
108
+
109
+ ### With venv
110
+ ```bash
111
+ python3.10 -m venv envs/lbm
112
+ source envs/lbm/bin/activate
113
+ ```
114
+
115
+ ### With conda
116
+ ```bash
117
+ conda create -n lbm python=3.10
118
+ conda activate lbm
119
+ ```
120
+
121
+ Then install the required dependencies and the repo in editable mode
122
+
123
+ ```bash
124
+ pip install --upgrade pip
125
+ pip install -e .
126
+ ```
127
+
128
+ ## Inference
129
+
130
+ We provide in `examples` a simple script to perform depth and normal estimation using the proposed method.
131
+
132
+ ```bash
133
+ python examples/inference/inference.py \
134
+ --model_name [depth|normals|relighting] \
135
+ --source_image path_to_your_image.jpg \
136
+ --output_path output_images
137
+ ```
138
+
139
+ See the trained models on the HF Hub 🤗
140
+ - [Surface normals Checkpoint](https://huggingface.co/jasperai/LBM_normals)
141
+ - [Depth Checkpoint](https://huggingface.co/jasperai/LBM_depth)
142
+ - [Relighting Checkpoint](https://huggingface.co/jasperai/LBM_relighting)
143
+
144
+ ## Local Gradio Demo
145
+ To run the local gradio demo, just run the following command:
146
+ ```bash
147
+ python examples/inference/gradio_demo.py
148
+ ```
149
+ It will download the pretrained model from the HF Hub as well as example images.
150
+
151
+ ## Training
152
+ We provide in `examples\training` an example of a script to train a LBM for surface normal predictions on [`hypersim`](https://github.com/apple/ml-hypersim) see [this](https://github.com/prs-eth/Marigold/blob/main/script/dataset_preprocess/hypersim/README.md) for data processing.
153
+
154
+ In `examples\trainig\configs`, you will find the configuration `yaml` associated to the training script. The only thing you need to do is to amend the `SHARDS_PATH_OR_URLS` section of the `yaml` so the model is trained on your own data.
155
+
156
+ Please note that this package uses [`webdataset`](https://github.com/webdataset/webdataset) to handle the datastream and so the urls you use should be fomatted according to the [`webdataset format`](https://github.com/webdataset/webdataset?tab=readme-ov-file#the-webdataset-format). In particular, for this example, each sample in your `.tar` files needs to be composed of a `jpg` file containing the image, a `normal.png` file containing the target normals as well as a `mask.png` containing a mask indicating the valid pixels
157
+
158
+ ```
159
+ sample = {
160
+ "jpg": source_image,
161
+ "normal.png": normals # target_image
162
+ "mask.png": mask # mask of valid pixels
163
+ }
164
+ ```
165
+
166
+ To train the model, you can use the following command:
167
+
168
+ ```bash
169
+ python examples/training/train_lbm_surface.py examples/training/config/surface.yaml
170
+ ```
171
+
172
+ *Note*: Make sure to update the relevant section of the `yaml` file to use your own data and log the results on your own [WandB](https://wandb.ai/site).
173
+
174
+ ## Citation
175
+ If you find this work useful or use it in your research, please consider citing us
176
+ ```bibtex
177
+ @article{chadebec2025lbm,
178
+ title={LBM: Latent Bridge Matching for Fast Image-to-Image Translation},
179
+ author={Clément Chadebec and Onur Tasar and Sanjeev Sreetharan and Benjamin Aubin},
180
+ year={2025},
181
+ journal = {arXiv preprint arXiv:2503.07535},
182
+ }
183
+ ```
assets/LBM.jpg ADDED

Git LFS Details

  • SHA256: 2f167343baabeab0fbded65d459f49e482fa3d2c3bbdc1d3fb7c957121183e04
  • Pointer size: 131 Bytes
  • Size of remote file: 457 kB
assets/depth_normal.jpg ADDED

Git LFS Details

  • SHA256: 92acb3a213336df332c10c67ab585eb8f6fe9dcdeabee36cf9b54324d07e00f4
  • Pointer size: 131 Bytes
  • Size of remote file: 372 kB
assets/object_removal.jpg ADDED

Git LFS Details

  • SHA256: a975d260a52741814260801fe1fedbc2f10d83e65d0b162eecba4cb0337c9a4c
  • Pointer size: 131 Bytes
  • Size of remote file: 427 kB
assets/relight.gif ADDED

Git LFS Details

  • SHA256: 8d3e522c726333f27616ef2c5f8d8bdc8cfc96fe266505ccefc09d2350cce4a4
  • Pointer size: 132 Bytes
  • Size of remote file: 6.27 MB
assets/relight.jpg ADDED

Git LFS Details

  • SHA256: f4e1469e4c10e91929fdb0a4c99d696fe5dcaf18751cb1e4822e7acd1230bcfe
  • Pointer size: 132 Bytes
  • Size of remote file: 1.49 MB
assets/relight_2.gif ADDED

Git LFS Details

  • SHA256: 86802558bd7406c2f2289dff88782ba829f6b64f06648bbded25232789f3d7e4
  • Pointer size: 131 Bytes
  • Size of remote file: 698 kB
assets/shadow_control.gif ADDED

Git LFS Details

  • SHA256: c3940de426dd87b7f11f6f75b666ddf3f49701bd92c76b654c4c8d039c3b87bc
  • Pointer size: 133 Bytes
  • Size of remote file: 11.3 MB
assets/upscaler.jpg ADDED

Git LFS Details

  • SHA256: d09ebb0b32567a2b751b637cb49708a9931ff22335db30c2d35528f6f0fa3f03
  • Pointer size: 132 Bytes
  • Size of remote file: 2.61 MB
examples/inference/gradio_demo.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import logging
3
+ import os
4
+ from copy import deepcopy
5
+
6
+ import gradio as gr
7
+ import numpy as np
8
+ import PIL
9
+ import torch
10
+ from huggingface_hub import snapshot_download
11
+ from PIL import Image
12
+ from torchvision.transforms import ToPILImage, ToTensor
13
+ from transformers import AutoModelForImageSegmentation
14
+ from utils import extract_object, resize_and_center_crop
15
+
16
+ from lbm.inference import get_model
17
+
18
+ PATH = os.path.dirname(os.path.abspath(__file__))
19
+ os.environ["GRADIO_TEMP_DIR"] = ".gradio"
20
+
21
+
22
+ if not os.path.exists(os.path.join(PATH, "ckpts", "relighting")):
23
+ logging.info(f"Downloading relighting LBM model from HF hub...")
24
+ model = get_model(
25
+ f"jasperai/LBM_relighting",
26
+ save_dir=os.path.join(PATH, "ckpts", "relighting"),
27
+ torch_dtype=torch.bfloat16,
28
+ device="cuda",
29
+ )
30
+ else:
31
+ model_dir = os.path.join(PATH, "ckpts", "relighting")
32
+ logging.info(f"Loading relighting LBM model from local...")
33
+ model = get_model(
34
+ os.path.join(PATH, "ckpts", "relighting"),
35
+ torch_dtype=torch.bfloat16,
36
+ device="cuda",
37
+ )
38
+
39
+ ASPECT_RATIOS = {
40
+ str(512 / 2048): (512, 2048),
41
+ str(1024 / 1024): (1024, 1024),
42
+ str(2048 / 512): (2048, 512),
43
+ str(896 / 1152): (896, 1152),
44
+ str(1152 / 896): (1152, 896),
45
+ str(512 / 1920): (512, 1920),
46
+ str(640 / 1536): (640, 1536),
47
+ str(768 / 1280): (768, 1280),
48
+ str(1280 / 768): (1280, 768),
49
+ str(1536 / 640): (1536, 640),
50
+ str(1920 / 512): (1920, 512),
51
+ }
52
+
53
+ birefnet = AutoModelForImageSegmentation.from_pretrained(
54
+ "ZhengPeng7/BiRefNet", trust_remote_code=True
55
+ ).cuda()
56
+ image_size = (1024, 1024)
57
+
58
+ if not os.path.exists(os.path.join(PATH, "examples")):
59
+ logging.info(f"Downloading backgrounds from HF hub...")
60
+ _ = snapshot_download(
61
+ "jasperai/LBM_relighting",
62
+ repo_type="space",
63
+ allow_patterns="*.jpg",
64
+ local_dir=PATH,
65
+ )
66
+
67
+
68
+ def evaluate(
69
+ fg_image: PIL.Image.Image,
70
+ bg_image: PIL.Image.Image,
71
+ num_sampling_steps: int = 1,
72
+ ):
73
+
74
+ ori_h_bg, ori_w_bg = fg_image.size
75
+ ar_bg = ori_h_bg / ori_w_bg
76
+ closest_ar_bg = min(ASPECT_RATIOS, key=lambda x: abs(float(x) - ar_bg))
77
+ dimensions_bg = ASPECT_RATIOS[closest_ar_bg]
78
+
79
+ _, fg_mask = extract_object(birefnet, deepcopy(fg_image))
80
+
81
+ fg_image = resize_and_center_crop(fg_image, dimensions_bg[0], dimensions_bg[1])
82
+ fg_mask = resize_and_center_crop(fg_mask, dimensions_bg[0], dimensions_bg[1])
83
+ bg_image = resize_and_center_crop(bg_image, dimensions_bg[0], dimensions_bg[1])
84
+
85
+ img_pasted = Image.composite(fg_image, bg_image, fg_mask)
86
+
87
+ img_pasted_tensor = ToTensor()(img_pasted).unsqueeze(0) * 2 - 1
88
+ batch = {
89
+ "source_image": img_pasted_tensor.cuda().to(torch.bfloat16),
90
+ }
91
+
92
+ z_source = model.vae.encode(batch[model.source_key])
93
+
94
+ output_image = model.sample(
95
+ z=z_source,
96
+ num_steps=num_sampling_steps,
97
+ conditioner_inputs=batch,
98
+ max_samples=1,
99
+ ).clamp(-1, 1)
100
+
101
+ output_image = (output_image[0].float().cpu() + 1) / 2
102
+ output_image = ToPILImage()(output_image)
103
+
104
+ # paste the output image on the background image
105
+ output_image = Image.composite(output_image, bg_image, fg_mask)
106
+
107
+ output_image.resize((ori_h_bg, ori_w_bg))
108
+
109
+ return (np.array(img_pasted), np.array(output_image))
110
+
111
+
112
+ with gr.Blocks(title="LBM Object Relighting") as demo:
113
+ gr.Markdown(
114
+ f"""
115
+ # Object Relighting with Latent Bridge Matching
116
+ This is an interactive demo of [LBM: Latent Bridge Matching for Fast Image-to-Image Translation](https://arxiv.org/abs/2503.07535) *by Jasper Research*. This demo is based on the [LBM relighting checkpoint](https://huggingface.co/jasperai/LBM_relighting).
117
+ """
118
+ )
119
+ gr.Markdown(
120
+ """
121
+ If you enjoy the space, please also promote *open-source* by giving a ⭐ to the <a href='https://github.com/gojasper/LBM' target='_blank'>Github Repo</a>.
122
+ """
123
+ )
124
+
125
+ with gr.Row():
126
+ with gr.Column():
127
+ with gr.Row():
128
+ fg_image = gr.Image(
129
+ type="pil",
130
+ label="Input Image",
131
+ image_mode="RGB",
132
+ height=360,
133
+ # width=360,
134
+ )
135
+ bg_image = gr.Image(
136
+ type="pil",
137
+ label="Target Background",
138
+ image_mode="RGB",
139
+ height=360,
140
+ # width=360,
141
+ )
142
+
143
+ with gr.Row():
144
+ submit_button = gr.Button("Relight", variant="primary")
145
+ with gr.Row():
146
+ num_inference_steps = gr.Slider(
147
+ minimum=1,
148
+ maximum=4,
149
+ value=1,
150
+ step=1,
151
+ label="Number of Inference Steps",
152
+ )
153
+
154
+ bg_gallery = gr.Gallery(
155
+ # height=450,
156
+ object_fit="contain",
157
+ label="Background List",
158
+ value=[
159
+ path
160
+ for path in glob.glob(
161
+ os.path.join(PATH, "examples/backgrounds/*.jpg")
162
+ )
163
+ ],
164
+ columns=5,
165
+ allow_preview=False,
166
+ )
167
+
168
+ with gr.Column():
169
+ output_slider = gr.ImageSlider(label="Composite vs LBM", type="numpy")
170
+ output_slider.upload(
171
+ fn=evaluate,
172
+ inputs=[fg_image, bg_image, num_inference_steps],
173
+ outputs=[output_slider],
174
+ )
175
+
176
+ submit_button.click(
177
+ evaluate,
178
+ inputs=[fg_image, bg_image, num_inference_steps],
179
+ outputs=[output_slider],
180
+ )
181
+
182
+ with gr.Row():
183
+ gr.Examples(
184
+ fn=evaluate,
185
+ examples=[
186
+ [
187
+ os.path.join(PATH, "examples/foregrounds/2.jpg"),
188
+ os.path.join(PATH, "examples/backgrounds/14.jpg"),
189
+ 1,
190
+ ],
191
+ [
192
+ os.path.join(PATH, "examples/foregrounds/10.jpg"),
193
+ os.path.join(PATH, "examples/backgrounds/4.jpg"),
194
+ 1,
195
+ ],
196
+ [
197
+ os.path.join(PATH, "examples/foregrounds/11.jpg"),
198
+ os.path.join(PATH, "examples/backgrounds/24.jpg"),
199
+ 1,
200
+ ],
201
+ [
202
+ os.path.join(PATH, "examples/foregrounds/19.jpg"),
203
+ os.path.join(PATH, "examples/backgrounds/3.jpg"),
204
+ 1,
205
+ ],
206
+ [
207
+ os.path.join(PATH, "examples/foregrounds/4.jpg"),
208
+ os.path.join(PATH, "examples/backgrounds/6.jpg"),
209
+ 1,
210
+ ],
211
+ [
212
+ os.path.join(PATH, "examples/foregrounds/14.jpg"),
213
+ os.path.join(PATH, "examples/backgrounds/22.jpg"),
214
+ 1,
215
+ ],
216
+ [
217
+ os.path.join(PATH, "examples/foregrounds/12.jpg"),
218
+ os.path.join(PATH, "examples/backgrounds/1.jpg"),
219
+ 1,
220
+ ],
221
+ ],
222
+ inputs=[fg_image, bg_image, num_inference_steps],
223
+ outputs=[output_slider],
224
+ run_on_click=True,
225
+ )
226
+
227
+ def bg_gallery_selected(gal, evt: gr.SelectData):
228
+ return gal[evt.index][0]
229
+
230
+ bg_gallery.select(bg_gallery_selected, inputs=bg_gallery, outputs=bg_image)
231
+
232
+ if __name__ == "__main__":
233
+
234
+ demo.launch(share=True)
examples/inference/inference.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+
5
+ import torch
6
+ from PIL import Image
7
+
8
+ from lbm.inference import evaluate, get_model
9
+
10
+ PATH = os.path.dirname(os.path.abspath(__file__))
11
+
12
+ logging.basicConfig(level=logging.INFO)
13
+
14
+ parser = argparse.ArgumentParser()
15
+ parser.add_argument("--source_image", type=str, required=True)
16
+ parser.add_argument("--output_path", type=str, required=True)
17
+ parser.add_argument("--num_inference_steps", type=int, default=1)
18
+ parser.add_argument(
19
+ "--model_name",
20
+ type=str,
21
+ default="normals",
22
+ choices=["normals", "depth", "relighting"],
23
+ )
24
+
25
+
26
+ args = parser.parse_args()
27
+
28
+
29
+ def main():
30
+ # download the weights from HF hub
31
+ if not os.path.exists(os.path.join(PATH, "ckpts", f"{args.model_name}")):
32
+ logging.info(f"Downloading {args.model_name} LBM model from HF hub...")
33
+ model = get_model(
34
+ f"jasperai/LBM_{args.model_name}",
35
+ save_dir=os.path.join(PATH, "ckpts", f"{args.model_name}"),
36
+ torch_dtype=torch.bfloat16,
37
+ device="cuda",
38
+ )
39
+
40
+ else:
41
+ model_dir = os.path.join(PATH, "ckpts", f"{args.model_name}")
42
+ logging.info(f"Loading {args.model_name} LBM model from local...")
43
+ model = get_model(model_dir, torch_dtype=torch.bfloat16, device="cuda")
44
+
45
+ source_image = Image.open(args.source_image).convert("RGB")
46
+
47
+ output_image = evaluate(model, source_image, args.num_inference_steps)
48
+
49
+ os.makedirs(args.output_path, exist_ok=True)
50
+
51
+ source_image.save(os.path.join(args.output_path, "source_image.jpg"))
52
+ output_image.save(os.path.join(args.output_path, "output_image.jpg"))
53
+
54
+ del model
55
+ torch.cuda.empty_cache()
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
examples/inference/utils.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ from torchvision import transforms
4
+
5
+
6
+ def extract_object(birefnet, img):
7
+ # Data settings
8
+ image_size = (1024, 1024)
9
+ transform_image = transforms.Compose(
10
+ [
11
+ transforms.Resize(image_size),
12
+ transforms.ToTensor(),
13
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
14
+ ]
15
+ )
16
+
17
+ image = img
18
+ input_images = transform_image(image).unsqueeze(0).cuda()
19
+
20
+ # Prediction
21
+ with torch.no_grad():
22
+ preds = birefnet(input_images)[-1].sigmoid().cpu()
23
+ pred = preds[0].squeeze()
24
+ pred_pil = transforms.ToPILImage()(pred)
25
+ mask = pred_pil.resize(image.size)
26
+ image = Image.composite(image, Image.new("RGB", image.size, (127, 127, 127)), mask)
27
+ return image, mask
28
+
29
+
30
+ def resize_and_center_crop(image, target_width, target_height):
31
+ original_width, original_height = image.size
32
+ scale_factor = max(target_width / original_width, target_height / original_height)
33
+ resized_width = int(round(original_width * scale_factor))
34
+ resized_height = int(round(original_height * scale_factor))
35
+ resized_image = image.resize((resized_width, resized_height), Image.LANCZOS)
36
+ left = (resized_width - target_width) / 2
37
+ top = (resized_height - target_height) / 2
38
+ right = (resized_width + target_width) / 2
39
+ bottom = (resized_height + target_height) / 2
40
+ cropped_image = resized_image.crop((left, top, right, bottom))
41
+ return cropped_image
examples/training/config/surface.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wandb
2
+ wandb_project: lbm-surface-flows
3
+ timestep_sampling: custom_timesteps
4
+ unet_input_channels: 4
5
+ vae_num_channels: 4
6
+ selected_timesteps: [250, 500, 750, 1000]
7
+ prob: [0.25, 0.25, 0.25, 0.25]
8
+ pixel_loss_type: lpips # l1 l2
9
+ pixel_loss_weight: 10.0
10
+ latent_loss_type: l2 # l1 l2
11
+ latent_loss_weight: 1.0
12
+ bridge_noise_sigma: 0.005
13
+ conditioning_images_keys: []
14
+ conditioning_masks_keys: []
15
+
16
+ # SHARDS_PATH_OR_URLS
17
+ train_shards:
18
+ - pipe:cat PATH_TO_TRAIN_TARS
19
+
20
+ validation_shards:
21
+ - pipe:cat PATH_TO_VAL_TARS
22
+
23
+ batch_size: 4
24
+ learning_rate: 4e-5
25
+ optimizer: AdamW
26
+ num_steps: [1, 4]
27
+ log_interval: 500
28
+ resume_from_checkpoint: true
29
+ max_epochs: 50
30
+ save_interval: 5000
31
+ save_ckpt_path: ./checkpoints
examples/training/train_lbm_surface.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import logging
3
+ import os
4
+ import random
5
+ import re
6
+ import shutil
7
+ from typing import List, Optional
8
+
9
+ import braceexpand
10
+ import fire
11
+ import torch
12
+ import yaml
13
+ from diffusers import FlowMatchEulerDiscreteScheduler, StableDiffusionXLPipeline
14
+ from diffusers.models import UNet2DConditionModel
15
+ from diffusers.models.attention import BasicTransformerBlock
16
+ from diffusers.models.resnet import ResnetBlock2D
17
+ from pytorch_lightning import Trainer, loggers
18
+ from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
19
+ from pytorch_lightning.strategies import FSDPStrategy
20
+ from torch.distributed.fsdp.wrap import ModuleWrapPolicy
21
+ from torchvision.transforms import InterpolationMode
22
+
23
+ from lbm.data.datasets import DataModule, DataModuleConfig
24
+ from lbm.data.filters import KeyFilter, KeyFilterConfig
25
+ from lbm.data.mappers import (
26
+ KeyRenameMapper,
27
+ KeyRenameMapperConfig,
28
+ MapperWrapper,
29
+ RescaleMapper,
30
+ RescaleMapperConfig,
31
+ TorchvisionMapper,
32
+ TorchvisionMapperConfig,
33
+ )
34
+ from lbm.models.embedders import (
35
+ ConditionerWrapper,
36
+ LatentsConcatEmbedder,
37
+ LatentsConcatEmbedderConfig,
38
+ )
39
+ from lbm.models.lbm import LBMConfig, LBMModel
40
+ from lbm.models.unets import DiffusersUNet2DCondWrapper
41
+ from lbm.models.vae import AutoencoderKLDiffusers, AutoencoderKLDiffusersConfig
42
+ from lbm.trainer import TrainingConfig, TrainingPipeline
43
+ from lbm.trainer.loggers import WandbSampleLogger
44
+ from lbm.trainer.utils import StateDictAdapter
45
+
46
+
47
+ def get_model(
48
+ backbone_signature: str = "stabilityai/stable-diffusion-xl-base-1.0",
49
+ vae_num_channels: int = 4,
50
+ unet_input_channels: int = 4,
51
+ timestep_sampling: str = "log_normal",
52
+ selected_timesteps: Optional[List[float]] = None,
53
+ prob: Optional[List[float]] = None,
54
+ conditioning_images_keys: Optional[List[str]] = [],
55
+ conditioning_masks_keys: Optional[List[str]] = [],
56
+ source_key: str = "source_image",
57
+ target_key: str = "source_image_paste",
58
+ mask_key: str = "mask",
59
+ bridge_noise_sigma: float = 0.0,
60
+ logit_mean: float = 0.0,
61
+ logit_std: float = 1.0,
62
+ pixel_loss_type: str = "lpips",
63
+ latent_loss_type: str = "l2",
64
+ latent_loss_weight: float = 1.0,
65
+ pixel_loss_weight: float = 0.0,
66
+ ):
67
+
68
+ conditioners = []
69
+
70
+ # Load pretrained model as base
71
+ pipe = StableDiffusionXLPipeline.from_pretrained(
72
+ backbone_signature,
73
+ torch_dtype=torch.bfloat16,
74
+ )
75
+
76
+ ### MMMDiT ###
77
+ # Get Architecture
78
+ denoiser = DiffusersUNet2DCondWrapper(
79
+ in_channels=unet_input_channels, # Add downsampled_image
80
+ out_channels=vae_num_channels,
81
+ center_input_sample=False,
82
+ flip_sin_to_cos=True,
83
+ freq_shift=0,
84
+ down_block_types=[
85
+ "DownBlock2D",
86
+ "CrossAttnDownBlock2D",
87
+ "CrossAttnDownBlock2D",
88
+ ],
89
+ mid_block_type="UNetMidBlock2DCrossAttn",
90
+ up_block_types=["CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D"],
91
+ only_cross_attention=False,
92
+ block_out_channels=[320, 640, 1280],
93
+ layers_per_block=2,
94
+ downsample_padding=1,
95
+ mid_block_scale_factor=1,
96
+ dropout=0.0,
97
+ act_fn="silu",
98
+ norm_num_groups=32,
99
+ norm_eps=1e-05,
100
+ cross_attention_dim=[320, 640, 1280],
101
+ transformer_layers_per_block=[1, 2, 10],
102
+ reverse_transformer_layers_per_block=None,
103
+ encoder_hid_dim=None,
104
+ encoder_hid_dim_type=None,
105
+ attention_head_dim=[5, 10, 20],
106
+ num_attention_heads=None,
107
+ dual_cross_attention=False,
108
+ use_linear_projection=True,
109
+ class_embed_type=None,
110
+ addition_embed_type=None,
111
+ addition_time_embed_dim=None,
112
+ num_class_embeds=None,
113
+ upcast_attention=None,
114
+ resnet_time_scale_shift="default",
115
+ resnet_skip_time_act=False,
116
+ resnet_out_scale_factor=1.0,
117
+ time_embedding_type="positional",
118
+ time_embedding_dim=None,
119
+ time_embedding_act_fn=None,
120
+ timestep_post_act=None,
121
+ time_cond_proj_dim=None,
122
+ conv_in_kernel=3,
123
+ conv_out_kernel=3,
124
+ projection_class_embeddings_input_dim=None,
125
+ attention_type="default",
126
+ class_embeddings_concat=False,
127
+ mid_block_only_cross_attention=None,
128
+ cross_attention_norm=None,
129
+ addition_embed_type_num_heads=64,
130
+ ).to(torch.bfloat16)
131
+
132
+ state_dict = pipe.unet.state_dict()
133
+
134
+ del state_dict["add_embedding.linear_1.weight"]
135
+ del state_dict["add_embedding.linear_1.bias"]
136
+ del state_dict["add_embedding.linear_2.weight"]
137
+ del state_dict["add_embedding.linear_2.bias"]
138
+
139
+ # Adapt the shapes
140
+ state_dict_adapter = StateDictAdapter()
141
+ state_dict = state_dict_adapter(
142
+ model_state_dict=denoiser.state_dict(),
143
+ checkpoint_state_dict=state_dict,
144
+ regex_keys=[
145
+ r"class_embedding.linear_\d+.(weight|bias)",
146
+ r"conv_in.weight",
147
+ r"(down_blocks|up_blocks)\.\d+\.attentions\.\d+\.transformer_blocks\.\d+\.attn\d+\.(to_k|to_v)\.weight",
148
+ r"mid_block\.attentions\.\d+\.transformer_blocks\.\d+\.attn\d+\.(to_k|to_v)\.weight",
149
+ ],
150
+ strategy="zeros",
151
+ )
152
+
153
+ denoiser.load_state_dict(state_dict, strict=True)
154
+
155
+ del pipe
156
+
157
+ if conditioning_images_keys != [] or conditioning_masks_keys != []:
158
+
159
+ latents_concat_embedder_config = LatentsConcatEmbedderConfig(
160
+ image_keys=conditioning_images_keys,
161
+ mask_keys=conditioning_masks_keys,
162
+ )
163
+ latent_concat_embedder = LatentsConcatEmbedder(latents_concat_embedder_config)
164
+ latent_concat_embedder.freeze()
165
+ conditioners.append(latent_concat_embedder)
166
+
167
+ # Wrap conditioners and set to device
168
+ conditioner = ConditionerWrapper(
169
+ conditioners=conditioners,
170
+ )
171
+
172
+ ## VAE ##
173
+ # Get VAE model
174
+ vae_config = AutoencoderKLDiffusersConfig(
175
+ version=backbone_signature,
176
+ subfolder="vae",
177
+ tiling_size=(128, 128),
178
+ )
179
+ vae = AutoencoderKLDiffusers(vae_config)
180
+ vae.freeze()
181
+ vae.to(torch.bfloat16)
182
+
183
+ # LBM Config
184
+ config = LBMConfig(
185
+ ucg_keys=None,
186
+ source_key=source_key,
187
+ target_key=target_key,
188
+ mask_key=mask_key,
189
+ latent_loss_weight=latent_loss_weight,
190
+ latent_loss_type=latent_loss_type,
191
+ pixel_loss_type=pixel_loss_type,
192
+ pixel_loss_weight=pixel_loss_weight,
193
+ timestep_sampling=timestep_sampling,
194
+ logit_mean=logit_mean,
195
+ logit_std=logit_std,
196
+ selected_timesteps=selected_timesteps,
197
+ prob=prob,
198
+ bridge_noise_sigma=bridge_noise_sigma,
199
+ )
200
+
201
+ training_noise_scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
202
+ backbone_signature,
203
+ subfolder="scheduler",
204
+ )
205
+ sampling_noise_scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
206
+ backbone_signature,
207
+ subfolder="scheduler",
208
+ )
209
+
210
+ # LBM Model
211
+ model = LBMModel(
212
+ config,
213
+ denoiser=denoiser,
214
+ training_noise_scheduler=training_noise_scheduler,
215
+ sampling_noise_scheduler=sampling_noise_scheduler,
216
+ vae=vae,
217
+ conditioner=conditioner,
218
+ ).to(torch.bfloat16)
219
+
220
+ return model
221
+
222
+
223
+ def get_filter_mappers():
224
+ filters_mappers = [
225
+ KeyFilter(KeyFilterConfig(keys=["jpg", "normal_aligned.png", "mask.png"])),
226
+ MapperWrapper(
227
+ [
228
+ KeyRenameMapper(
229
+ KeyRenameMapperConfig(
230
+ key_map={
231
+ "jpg": "image",
232
+ "normal_aligned.png": "normal",
233
+ "mask.png": "mask",
234
+ }
235
+ )
236
+ ),
237
+ TorchvisionMapper(
238
+ TorchvisionMapperConfig(
239
+ key="image",
240
+ transforms=["ToTensor", "Resize"],
241
+ transforms_kwargs=[
242
+ {},
243
+ {
244
+ "size": (480, 640),
245
+ "interpolation": InterpolationMode.NEAREST_EXACT,
246
+ },
247
+ ],
248
+ )
249
+ ),
250
+ TorchvisionMapper(
251
+ TorchvisionMapperConfig(
252
+ key="normal",
253
+ transforms=["ToTensor", "Resize"],
254
+ transforms_kwargs=[
255
+ {},
256
+ {
257
+ "size": (480, 640),
258
+ "interpolation": InterpolationMode.NEAREST_EXACT,
259
+ },
260
+ ],
261
+ )
262
+ ),
263
+ TorchvisionMapper(
264
+ TorchvisionMapperConfig(
265
+ key="mask",
266
+ transforms=["ToTensor", "Resize", "Normalize"],
267
+ transforms_kwargs=[
268
+ {},
269
+ {
270
+ "size": (480, 640),
271
+ "interpolation": InterpolationMode.NEAREST_EXACT,
272
+ },
273
+ {"mean": 0.0, "std": 1.0},
274
+ ],
275
+ )
276
+ ),
277
+ RescaleMapper(RescaleMapperConfig(key="image")),
278
+ RescaleMapper(RescaleMapperConfig(key="normal")),
279
+ ],
280
+ ),
281
+ ]
282
+
283
+ return filters_mappers
284
+
285
+
286
+ def get_data_module(
287
+ train_shards: List[str],
288
+ validation_shards: List[str],
289
+ batch_size: int,
290
+ ):
291
+
292
+ # TRAIN
293
+ train_filters_mappers = get_filter_mappers()
294
+
295
+ # unbrace urls
296
+ train_shards_path_or_urls_unbraced = []
297
+ for train_shards_path_or_url in train_shards:
298
+ train_shards_path_or_urls_unbraced.extend(
299
+ braceexpand.braceexpand(train_shards_path_or_url)
300
+ )
301
+
302
+ # shuffle shards
303
+ random.shuffle(train_shards_path_or_urls_unbraced)
304
+
305
+ # data config
306
+ data_config = DataModuleConfig(
307
+ shards_path_or_urls=train_shards_path_or_urls_unbraced,
308
+ decoder="pil",
309
+ shuffle_before_split_by_node_buffer_size=20,
310
+ shuffle_before_split_by_workers_buffer_size=20,
311
+ shuffle_before_filter_mappers_buffer_size=20,
312
+ shuffle_after_filter_mappers_buffer_size=20,
313
+ per_worker_batch_size=batch_size,
314
+ num_workers=min(10, len(train_shards_path_or_urls_unbraced)),
315
+ )
316
+
317
+ train_data_config = data_config
318
+
319
+ # VALIDATION
320
+ validation_filters_mappers = get_filter_mappers()
321
+
322
+ # unbrace urls
323
+ validation_shards_path_or_urls_unbraced = []
324
+ for validation_shards_path_or_url in validation_shards:
325
+ validation_shards_path_or_urls_unbraced.extend(
326
+ braceexpand.braceexpand(validation_shards_path_or_url)
327
+ )
328
+
329
+ data_config = DataModuleConfig(
330
+ shards_path_or_urls=validation_shards_path_or_urls_unbraced,
331
+ decoder="pil",
332
+ shuffle_before_split_by_node_buffer_size=10,
333
+ shuffle_before_split_by_workers_buffer_size=10,
334
+ shuffle_before_filter_mappers_buffer_size=10,
335
+ shuffle_after_filter_mappers_buffer_size=10,
336
+ per_worker_batch_size=batch_size,
337
+ num_workers=min(10, len(train_shards_path_or_urls_unbraced)),
338
+ )
339
+
340
+ validation_data_config = data_config
341
+
342
+ # data module
343
+ data_module = DataModule(
344
+ train_config=train_data_config,
345
+ train_filters_mappers=train_filters_mappers,
346
+ eval_config=validation_data_config,
347
+ eval_filters_mappers=validation_filters_mappers,
348
+ )
349
+
350
+ return data_module
351
+
352
+
353
+ def main(
354
+ train_shards: List[str] = ["pipe:cat path/to/train/shards"],
355
+ validation_shards: List[str] = ["pipe:cat path/to/validation/shards"],
356
+ backbone_signature: str = "stabilityai/stable-diffusion-xl-base-1.0",
357
+ vae_num_channels: int = 4,
358
+ unet_input_channels: int = 4,
359
+ source_key: str = "image",
360
+ target_key: str = "normal",
361
+ mask_key: str = "mask",
362
+ wandb_project: str = "lbm-surface",
363
+ batch_size: int = 8,
364
+ num_steps: List[int] = [1, 2, 4],
365
+ learning_rate: float = 5e-5,
366
+ learning_rate_scheduler: str = None,
367
+ learning_rate_scheduler_kwargs: dict = {},
368
+ optimizer: str = "AdamW",
369
+ optimizer_kwargs: dict = {},
370
+ timestep_sampling: str = "uniform",
371
+ logit_mean: float = 0.0,
372
+ logit_std: float = 1.0,
373
+ pixel_loss_type: str = "lpips",
374
+ latent_loss_type: str = "l2",
375
+ latent_loss_weight: float = 1.0,
376
+ pixel_loss_weight: float = 0.0,
377
+ selected_timesteps: List[float] = None,
378
+ prob: List[float] = None,
379
+ conditioning_images_keys: Optional[List[str]] = [],
380
+ conditioning_masks_keys: Optional[List[str]] = [],
381
+ config_yaml: dict = None,
382
+ save_ckpt_path: str = "./checkpoints",
383
+ log_interval: int = 100,
384
+ resume_from_checkpoint: bool = True,
385
+ max_epochs: int = 100,
386
+ bridge_noise_sigma: float = 0.005,
387
+ save_interval: int = 1000,
388
+ path_config: str = None,
389
+ ):
390
+ model = get_model(
391
+ backbone_signature=backbone_signature,
392
+ vae_num_channels=vae_num_channels,
393
+ unet_input_channels=unet_input_channels,
394
+ source_key=source_key,
395
+ target_key=target_key,
396
+ mask_key=mask_key,
397
+ timestep_sampling=timestep_sampling,
398
+ logit_mean=logit_mean,
399
+ logit_std=logit_std,
400
+ pixel_loss_type=pixel_loss_type,
401
+ latent_loss_type=latent_loss_type,
402
+ latent_loss_weight=latent_loss_weight,
403
+ pixel_loss_weight=pixel_loss_weight,
404
+ selected_timesteps=selected_timesteps,
405
+ prob=prob,
406
+ conditioning_images_keys=conditioning_images_keys,
407
+ conditioning_masks_keys=conditioning_masks_keys,
408
+ bridge_noise_sigma=bridge_noise_sigma,
409
+ )
410
+
411
+ data_module = get_data_module(
412
+ train_shards=train_shards,
413
+ validation_shards=validation_shards,
414
+ batch_size=batch_size,
415
+ )
416
+
417
+ train_parameters = ["denoiser.*"]
418
+
419
+ # Training Config
420
+ training_config = TrainingConfig(
421
+ learning_rate=learning_rate,
422
+ lr_scheduler_name=learning_rate_scheduler,
423
+ lr_scheduler_kwargs=learning_rate_scheduler_kwargs,
424
+ log_keys=["image", "normal", "mask"],
425
+ trainable_params=train_parameters,
426
+ optimizer_name=optimizer,
427
+ optimizer_kwargs=optimizer_kwargs,
428
+ log_samples_model_kwargs={
429
+ "input_shape": None,
430
+ "num_steps": num_steps,
431
+ },
432
+ )
433
+ if (
434
+ os.path.exists(save_ckpt_path)
435
+ and resume_from_checkpoint
436
+ and "last.ckpt" in os.listdir(save_ckpt_path)
437
+ ):
438
+ start_ckpt = f"{save_ckpt_path}/last.ckpt"
439
+ print(f"Resuming from checkpoint: {start_ckpt}")
440
+
441
+ else:
442
+ start_ckpt = None
443
+
444
+ pipeline = TrainingPipeline(model=model, pipeline_config=training_config)
445
+
446
+ pipeline.save_hyperparameters(
447
+ {
448
+ f"embedder_{i}": embedder.config.to_dict()
449
+ for i, embedder in enumerate(model.conditioner.conditioners)
450
+ }
451
+ )
452
+
453
+ pipeline.save_hyperparameters(
454
+ {
455
+ "denoiser": model.denoiser.config,
456
+ "vae": model.vae.config.to_dict(),
457
+ "config_yaml": config_yaml,
458
+ "training": training_config.to_dict(),
459
+ "training_noise_scheduler": model.training_noise_scheduler.config,
460
+ "sampling_noise_scheduler": model.sampling_noise_scheduler.config,
461
+ }
462
+ )
463
+
464
+ training_signature = (
465
+ datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
466
+ + "-LBM-Surface"
467
+ + f"{os.environ['SLURM_JOB_ID']}"
468
+ + f"_{os.environ.get('SLURM_ARRAY_TASK_ID', 0)}"
469
+ )
470
+ dir_path = f"{save_ckpt_path}/logs/{training_signature}"
471
+ if os.environ["SLURM_PROCID"] == "0":
472
+ os.makedirs(dir_path, exist_ok=True)
473
+ if path_config is not None:
474
+ shutil.copy(path_config, f"{save_ckpt_path}/config.yaml")
475
+ run_name = training_signature
476
+
477
+ # Ignore parameters unused during training
478
+ ignore_states = []
479
+ for name, param in pipeline.model.named_parameters():
480
+ ignore = True
481
+ for regex in ["denoiser."]:
482
+ pattern = re.compile(regex)
483
+ if re.match(pattern, name):
484
+ ignore = False
485
+ if ignore:
486
+ ignore_states.append(param)
487
+
488
+ # FSDP Strategy
489
+ strategy = FSDPStrategy(
490
+ auto_wrap_policy=ModuleWrapPolicy(
491
+ [
492
+ UNet2DConditionModel,
493
+ BasicTransformerBlock,
494
+ ResnetBlock2D,
495
+ torch.nn.Conv2d,
496
+ ]
497
+ ),
498
+ activation_checkpointing_policy=ModuleWrapPolicy(
499
+ [
500
+ BasicTransformerBlock,
501
+ ResnetBlock2D,
502
+ ]
503
+ ),
504
+ sharding_strategy="SHARD_GRAD_OP",
505
+ ignored_states=ignore_states,
506
+ )
507
+
508
+ trainer = Trainer(
509
+ accelerator="gpu",
510
+ devices=int(os.environ["SLURM_NPROCS"]) // int(os.environ["SLURM_NNODES"]),
511
+ num_nodes=int(os.environ["SLURM_NNODES"]),
512
+ strategy=strategy,
513
+ default_root_dir="logs",
514
+ logger=loggers.WandbLogger(
515
+ project=wandb_project, offline=False, name=run_name, save_dir=save_ckpt_path
516
+ ),
517
+ callbacks=[
518
+ WandbSampleLogger(log_batch_freq=log_interval),
519
+ LearningRateMonitor(logging_interval="step"),
520
+ ModelCheckpoint(
521
+ dirpath=save_ckpt_path,
522
+ every_n_train_steps=save_interval,
523
+ save_last=True,
524
+ ),
525
+ ],
526
+ num_sanity_val_steps=0,
527
+ precision="bf16-mixed",
528
+ limit_val_batches=2,
529
+ val_check_interval=1000,
530
+ max_epochs=max_epochs,
531
+ )
532
+
533
+ trainer.fit(pipeline, data_module, ckpt_path=start_ckpt)
534
+
535
+
536
+ def main_from_config(path_config: str = None):
537
+ with open(path_config, "r") as file:
538
+ config = yaml.safe_load(file)
539
+ logging.info(
540
+ f"Running main with config: {yaml.dump(config, default_flow_style=False)}"
541
+ )
542
+ main(**config, config_yaml=config, path_config=path_config)
543
+
544
+
545
+ if __name__ == "__main__":
546
+ fire.Fire(main_from_config)
frpc_linux_amd64_v0.3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c791d1f047b41ff5885772fc4bf20b797c6059bbd82abb9e31de15e55d6a57c4
3
+ size 11907224
img/input_img/1.jpg ADDED
img/output_img/output_image.jpg ADDED
img/output_img/source_image.jpg ADDED
pyproject.toml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-requirements-txt"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "lbm"
7
+ dynamic = ["dependencies", "optional-dependencies"]
8
+ description = "LBM: Latent Bridge Matching for Fast Image-to-Image Translation"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ authors = [
12
+ { name = "Clement Chadebec", email = "[email protected]" },
13
+ { name = "Benjamin Aubin", email = "[email protected]" },
14
+ ]
15
+ maintainers = [
16
+ { name = "Clement Chadebec", email = "[email protected]" },
17
+ ]
18
+ classifiers = [
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "License :: OSI Approved :: Apache Software License",
24
+ "Operating System :: OS Independent",
25
+ ]
26
+ version = "0.1"
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/gojasper/LBM"
30
+ Repository = "https://github.com/gojasper/LBM"
31
+
32
+ [tool.hatch.metadata]
33
+ allow-direct-references = true
34
+
35
+ [tool.hatch.metadata.hooks.requirements_txt]
36
+ files = ["requirements.txt"]
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/lbm"]
requirements.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # accelerate==1.4.0
2
+ diffusers==0.32.2
3
+ torch==2.7.0
4
+ torchvision>=0.20.0
5
+ black==24.2.0
6
+ einops==0.7.0
7
+ fire>=0.5.0
8
+ gradio==5.29.0
9
+ isort==5.13.2
10
+ lightning==2.5.0
11
+ lpips==0.1.4
12
+ opencv-python==4.9.0.80
13
+ peft==0.9.0
14
+ pydantic>=2.6.1
15
+ scipy>=1.12.0
16
+ sentencepiece>=0.2.0
17
+ timm==0.9.16
18
+ tokenizers>=0.15.2
19
+ torch-fidelity>=0.3.0
20
+ torchmetrics>=1.3.1
21
+ transformers==4.42.3
22
+ wandb==0.16.2
23
+ webdataset>=0.2.86
24
+ kornia==0.8.0
src/lbm/config.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import warnings
4
+ from dataclasses import asdict, field
5
+ from typing import Any, Dict, Union
6
+
7
+ import yaml
8
+ from pydantic import ValidationError
9
+ from pydantic.dataclasses import dataclass
10
+ from yaml import safe_load
11
+
12
+
13
+ @dataclass
14
+ class BaseConfig:
15
+ """This is the BaseConfig class which defines all the useful loading and saving methods
16
+ of the configs"""
17
+
18
+ name: str = field(init=False)
19
+
20
+ def __post_init__(self):
21
+ self.name = self.__class__.__name__
22
+
23
+ @classmethod
24
+ def from_dict(cls, config_dict: Dict[str, Any]) -> "BaseConfig":
25
+ """Creates a BaseConfig instance from a dictionnary
26
+
27
+ Args:
28
+ config_dict (dict): The Python dictionnary containing all the parameters
29
+
30
+ Returns:
31
+ :class:`BaseConfig`: The created instance
32
+ """
33
+ try:
34
+ config = cls(**config_dict)
35
+ except (ValidationError, TypeError) as e:
36
+ raise e
37
+ return config
38
+
39
+ @classmethod
40
+ def _dict_from_json(cls, json_path: Union[str, os.PathLike]) -> Dict[str, Any]:
41
+ try:
42
+ with open(json_path) as f:
43
+ try:
44
+ config_dict = json.load(f)
45
+ return config_dict
46
+
47
+ except (TypeError, json.JSONDecodeError) as e:
48
+ raise TypeError(
49
+ f"File {json_path} not loadable. Maybe not json ? \n"
50
+ f"Catch Exception {type(e)} with message: " + str(e)
51
+ ) from e
52
+
53
+ except FileNotFoundError:
54
+ raise FileNotFoundError(
55
+ f"Config file not found. Please check path '{json_path}'"
56
+ )
57
+
58
+ @classmethod
59
+ def from_json(cls, json_path: str) -> "BaseConfig":
60
+ """Creates a BaseConfig instance from a JSON config file
61
+
62
+ Args:
63
+ json_path (str): The path to the json file containing all the parameters
64
+
65
+ Returns:
66
+ :class:`BaseConfig`: The created instance
67
+ """
68
+ config_dict = cls._dict_from_json(json_path)
69
+
70
+ config_name = config_dict.pop("name")
71
+
72
+ if cls.__name__ != config_name:
73
+ warnings.warn(
74
+ f"You are trying to load a "
75
+ f"`{ cls.__name__}` while a "
76
+ f"`{config_name}` is given."
77
+ )
78
+
79
+ return cls.from_dict(config_dict)
80
+
81
+ def to_dict(self) -> dict:
82
+ """Transforms object into a Python dictionnary
83
+
84
+ Returns:
85
+ (dict): The dictionnary containing all the parameters"""
86
+ return asdict(self)
87
+
88
+ def to_json_string(self):
89
+ """Transforms object into a JSON string
90
+
91
+ Returns:
92
+ (str): The JSON str containing all the parameters"""
93
+ return json.dumps(self.to_dict())
94
+
95
+ def save_json(self, file_path: str):
96
+ """Saves a ``.json`` file from the dataclass
97
+
98
+ Args:
99
+ file_path (str): path to the file
100
+ """
101
+ with open(os.path.join(file_path), "w", encoding="utf-8") as fp:
102
+ fp.write(self.to_json_string())
103
+
104
+ def save_yaml(self, file_path: str):
105
+ """Saves a ``.yaml`` file from the dataclass
106
+
107
+ Args:
108
+ file_path (str): path to the file
109
+ """
110
+ with open(os.path.join(file_path), "w", encoding="utf-8") as fp:
111
+ yaml.dump(self.to_dict(), fp)
112
+
113
+ @classmethod
114
+ def from_yaml(cls, yaml_path: str) -> "BaseConfig":
115
+ """Creates a BaseConfig instance from a YAML config file
116
+
117
+ Args:
118
+ yaml_path (str): The path to the yaml file containing all the parameters
119
+
120
+ Returns:
121
+ :class:`BaseConfig`: The created instance
122
+ """
123
+ with open(yaml_path, "r") as f:
124
+ try:
125
+ config_dict = safe_load(f)
126
+ except yaml.YAMLError as e:
127
+ raise yaml.YAMLError(
128
+ f"File {yaml_path} not loadable. Maybe not yaml ? \n"
129
+ f"Catch Exception {type(e)} with message: " + str(e)
130
+ ) from e
131
+
132
+ config_name = config_dict.pop("name")
133
+
134
+ if cls.__name__ != config_name:
135
+ warnings.warn(
136
+ f"You are trying to load a "
137
+ f"`{ cls.__name__}` while a "
138
+ f"`{config_name}` is given."
139
+ )
140
+
141
+ return cls.from_dict(config_dict)
src/lbm/data/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains a collection of data related classes and functions to train the :mod:`cr.models`.
3
+ In a training loop a batch of data is struvtued as a dictionnary on which the modules :mod:`cr.data.datasets`
4
+ and :mod:`cr.data.filters` allow to perform several operations.
5
+
6
+
7
+ Examples
8
+ ########
9
+
10
+ Create a DataModule to train a model
11
+
12
+ .. code-block::python
13
+
14
+ from cr.data import DataModule, DataModuleConfig
15
+ from cr.data.filters import KeyFilter, KeyFilterConfig
16
+ from cr.data.mappers import KeyRenameMapper, KeyRenameMapperConfig
17
+
18
+ # Create the filters and mappers
19
+ filters_mappers = [
20
+ KeyFilter(KeyFilterConfig(keys=["image", "txt"])),
21
+ KeyRenameMapper(
22
+ KeyRenameMapperConfig(key_map={"jpg": "image", "txt": "text"})
23
+ )
24
+ ]
25
+
26
+ # Create the DataModule
27
+ data_module = DataModule(
28
+ train_config=DataModuleConfig(
29
+ shards_path_or_urls="your urls or paths",
30
+ decoder="pil",
31
+ shuffle_buffer_size=100,
32
+ per_worker_batch_size=32,
33
+ num_workers=4,
34
+ ),
35
+ train_filters_mappers=filters_mappers,
36
+ eval_config=DataModuleConfig(
37
+ shards_path_or_urls="your urls or paths",
38
+ decoder="pil",
39
+ shuffle_buffer_size=100,
40
+ per_worker_batch_size=32,
41
+ num_workers=4,
42
+ ),
43
+ eval_filters_mappers=filters_mappers,
44
+ )
45
+
46
+ # This can then be passed to a :mod:`pytorch_lightning.Trainer` to train a model
47
+
48
+
49
+
50
+
51
+
52
+ The :mod:`cr.data` includes the following submodules:
53
+
54
+ - :mod:`cr.data.datasets`: a collection of :mod:`pytorch_lightning.LightningDataModule` used to train the models. In particular,
55
+ they can used to create the dataloaders and setup the data pipelines.
56
+ - :mod:`cr.data.filters`: a collection of filters used apply filters on a training batch of data/
57
+
58
+ """
59
+
60
+ from .datasets import DataModule
61
+
62
+ __all__ = ["DataModule"]
src/lbm/data/datasets/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A collection of :mod:`pytorch_lightning.LightningDataModule` used to train the models. In particular,
3
+ they can be used to create the dataloaders and setup the data pipelines.
4
+ """
5
+
6
+ from .dataset import DataModule
7
+ from .datasets_config import DataModuleConfig
8
+
9
+ __all__ = ["DataModule", "DataModuleConfig"]
src/lbm/data/datasets/collation_fn.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Union
2
+
3
+ import numpy as np
4
+ import torch
5
+
6
+
7
+ def custom_collation_fn(
8
+ samples: List[Dict[str, Union[int, float, np.ndarray, torch.Tensor]]],
9
+ combine_tensors: bool = True,
10
+ combine_scalars: bool = True,
11
+ ) -> dict:
12
+ """
13
+ Collate function for PyTorch DataLoader.
14
+
15
+ Args:
16
+ samples(List[Dict[str, Union[int, float, np.ndarray, torch.Tensor]]]): List of samples.
17
+ combine_tensors (bool): Whether to turn lists of tensors into a single tensor.
18
+ combine_scalars (bool): Whether to turn lists of scalars into a single ndarray.
19
+ """
20
+ keys = set.intersection(*[set(sample.keys()) for sample in samples])
21
+ batched = {key: [] for key in keys}
22
+ for s in samples:
23
+ [batched[key].append(s[key]) for key in batched]
24
+
25
+ result = {}
26
+ for key in batched:
27
+ if isinstance(batched[key][0], (int, float)):
28
+ if combine_scalars:
29
+ result[key] = np.array(list(batched[key]))
30
+ elif isinstance(batched[key][0], torch.Tensor):
31
+ if combine_tensors:
32
+ result[key] = torch.stack(list(batched[key]))
33
+ elif isinstance(batched[key][0], np.ndarray):
34
+ if combine_tensors:
35
+ result[key] = np.array(list(batched[key]))
36
+ else:
37
+ result[key] = list(batched[key])
38
+
39
+ del samples
40
+ del batched
41
+ return result
src/lbm/data/datasets/dataset.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Union
2
+
3
+ import pytorch_lightning as pl
4
+ import webdataset as wds
5
+ from webdataset import DataPipeline
6
+
7
+ from ..filters import BaseFilter, FilterWrapper
8
+ from ..mappers import BaseMapper, MapperWrapper
9
+ from .collation_fn import custom_collation_fn
10
+ from .datasets_config import DataModuleConfig
11
+
12
+
13
+ class DataPipeline:
14
+ """
15
+ DataPipeline class for creating a dataloader from a single configuration
16
+
17
+ Args:
18
+
19
+ config (DataModuleConfig):
20
+ Configuration for the dataset
21
+
22
+ filters_mappers (Union[List[Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]]):
23
+ List of filters and mappers for the dataset. These will be sequentially applied.
24
+
25
+ batched_filters_mappers (List[Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]]):
26
+ List of batched transforms for the dataset. These will be sequentially applied.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ config: DataModuleConfig,
32
+ filters_mappers: List[
33
+ Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]
34
+ ],
35
+ batched_filters_mappers: List[
36
+ Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]
37
+ ] = None,
38
+ ):
39
+ self.config = config
40
+ self.shards_path_or_urls = config.shards_path_or_urls
41
+ self.filters_mappers = filters_mappers
42
+ self.batched_filters_mappers = batched_filters_mappers or []
43
+
44
+ if filters_mappers is None:
45
+ filters_mappers = []
46
+
47
+ # set processing pipeline
48
+ self.processing_pipeline = [wds.decode(config.decoder, handler=config.handler)]
49
+ self.processing_pipeline.extend(
50
+ self._add_filters_mappers(
51
+ filters_mappers=filters_mappers,
52
+ handler=config.handler,
53
+ )
54
+ )
55
+
56
+ def _add_filters_mappers(
57
+ self,
58
+ filters_mappers: List[
59
+ Union[
60
+ FilterWrapper,
61
+ MapperWrapper,
62
+ ]
63
+ ],
64
+ handler: Callable = wds.warn_and_continue,
65
+ ) -> List[Union[FilterWrapper, MapperWrapper]]:
66
+ tmp_pipeline = []
67
+ for filter_mapper in filters_mappers:
68
+ if isinstance(filter_mapper, FilterWrapper) or isinstance(
69
+ filter_mapper, BaseFilter
70
+ ):
71
+ tmp_pipeline.append(wds.select(filter_mapper))
72
+ elif isinstance(filter_mapper, MapperWrapper) or isinstance(
73
+ filter_mapper, BaseMapper
74
+ ):
75
+ tmp_pipeline.append(wds.map(filter_mapper, handler=handler))
76
+ elif isinstance(filter_mapper) or isinstance(filter_mapper):
77
+ tmp_pipeline.append(wds.map(filter_mapper, handler=handler))
78
+ else:
79
+ raise ValueError("Unknown type of filter/mapper")
80
+ return tmp_pipeline
81
+
82
+ def setup(self):
83
+ pipeline = [wds.SimpleShardList(self.shards_path_or_urls)]
84
+
85
+ # shuffle before split by node
86
+ if self.config.shuffle_before_split_by_node_buffer_size is not None:
87
+ pipeline.append(
88
+ wds.shuffle(
89
+ self.config.shuffle_before_split_by_node_buffer_size,
90
+ handler=self.config.handler,
91
+ )
92
+ )
93
+ # split by node
94
+ pipeline.append(wds.split_by_node)
95
+
96
+ # shuffle before split by workers
97
+ if self.config.shuffle_before_split_by_workers_buffer_size is not None:
98
+ pipeline.append(
99
+ wds.shuffle(
100
+ self.config.shuffle_before_split_by_workers_buffer_size,
101
+ handler=self.config.handler,
102
+ )
103
+ )
104
+ # split by worker
105
+ pipeline.extend(
106
+ [
107
+ wds.split_by_worker,
108
+ wds.tarfile_to_samples(
109
+ handler=self.config.handler,
110
+ rename_files=self.config.rename_files_fn,
111
+ ),
112
+ ]
113
+ )
114
+
115
+ # shuffle before filter mappers
116
+ if self.config.shuffle_before_filter_mappers_buffer_size is not None:
117
+ pipeline.append(
118
+ wds.shuffle(
119
+ self.config.shuffle_before_filter_mappers_buffer_size,
120
+ handler=self.config.handler,
121
+ )
122
+ )
123
+
124
+ # apply filters and mappers
125
+ pipeline.extend(self.processing_pipeline)
126
+
127
+ # shuffle after filter mappers
128
+ if self.config.shuffle_after_filter_mappers_buffer_size is not None:
129
+ pipeline.append(
130
+ wds.shuffle(
131
+ self.config.shuffle_after_filter_mappers_buffer_size,
132
+ handler=self.config.handler,
133
+ ),
134
+ )
135
+
136
+ # batching
137
+ pipeline.append(
138
+ wds.batched(
139
+ self.config.per_worker_batch_size,
140
+ collation_fn=custom_collation_fn,
141
+ )
142
+ )
143
+
144
+ # apply batched transforms
145
+ pipeline.extend(
146
+ self._add_filters_mappers(
147
+ filters_mappers=self.batched_filters_mappers,
148
+ handler=self.config.handler,
149
+ )
150
+ )
151
+
152
+ # create the data pipeline
153
+ pipeline = wds.DataPipeline(*pipeline, handler=self.config.handler)
154
+
155
+ # set the pipeline
156
+ self.pipeline = pipeline
157
+
158
+ def dataloader(self):
159
+ # return the loader
160
+ return wds.WebLoader(
161
+ self.pipeline,
162
+ batch_size=None,
163
+ num_workers=self.config.num_workers,
164
+ )
165
+
166
+
167
+ class DataModule(pl.LightningDataModule):
168
+ """
169
+ Main DataModule class for creating data loaders and training/evaluating models
170
+
171
+ Args:
172
+
173
+ train_config (DataModuleConfig):
174
+ Configuration for the training dataset
175
+
176
+ train_filters_mappers (Union[List[Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]]):
177
+ List of filters and mappers for the training dataset. These will be sequentially applied.
178
+
179
+ train_batched_filters_mappers (List[Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]]):
180
+ List of batched transforms for the training dataset. These will be sequentially applied.
181
+
182
+ eval_config (DataModuleConfig):
183
+ Configuration for the evaluation dataset
184
+
185
+ eval_filters_mappers (List[Union[FilterWrapper, MapperWrapper]]):
186
+ List of filters and mappers for the evaluation dataset.These will be sequentially applied.
187
+
188
+ eval_batched_filters_mappers (List[Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]]):
189
+ List of batched transforms for the evaluation dataset. These will be sequentially applied.
190
+ """
191
+
192
+ def __init__(
193
+ self,
194
+ train_config: DataModuleConfig,
195
+ train_filters_mappers: List[
196
+ Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]
197
+ ] = None,
198
+ train_batched_filters_mappers: List[
199
+ Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]
200
+ ] = None,
201
+ eval_config: DataModuleConfig = None,
202
+ eval_filters_mappers: List[Union[FilterWrapper, MapperWrapper]] = None,
203
+ eval_batched_filters_mappers: List[
204
+ Union[BaseMapper, BaseFilter, FilterWrapper, MapperWrapper]
205
+ ] = None,
206
+ ):
207
+ super().__init__()
208
+
209
+ self.train_config = train_config
210
+ self.train_filters_mappers = train_filters_mappers
211
+ self.train_batched_filters_mappers = train_batched_filters_mappers
212
+
213
+ self.eval_config = eval_config
214
+ self.eval_filters_mappers = eval_filters_mappers
215
+ self.eval_batched_filters_mappers = eval_batched_filters_mappers
216
+
217
+ def setup(self, stage=None):
218
+ """
219
+ Setup the data module and create the webdataset processing pipelines
220
+ """
221
+
222
+ # train pipeline
223
+ self.train_pipeline = DataPipeline(
224
+ config=self.train_config,
225
+ filters_mappers=self.train_filters_mappers,
226
+ batched_filters_mappers=self.train_batched_filters_mappers,
227
+ )
228
+ self.train_pipeline.setup()
229
+
230
+ # eval pipeline
231
+ if self.eval_config is not None:
232
+ self.eval_pipeline = DataPipeline(
233
+ config=self.eval_config,
234
+ filters_mappers=self.eval_filters_mappers,
235
+ batched_filters_mappers=self.eval_batched_filters_mappers,
236
+ )
237
+ self.eval_pipeline.setup()
238
+
239
+ def train_dataloader(self):
240
+ return self.train_pipeline.dataloader()
241
+
242
+ def val_dataloader(self):
243
+ return self.eval_pipeline.dataloader()
src/lbm/data/datasets/datasets_config.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional, Union
2
+
3
+ import webdataset as wds
4
+ from pydantic.dataclasses import dataclass
5
+
6
+ from ...config import BaseConfig
7
+
8
+
9
+ @dataclass
10
+ class DataModuleConfig(BaseConfig):
11
+ """
12
+ Configuration for the DataModule
13
+
14
+ Args:
15
+
16
+ shards_path_or_urls (Union[str, List[str]]): The path or url to the shards. Defaults to None.
17
+ per_worker_batch_size (int): The batch size for the dataset. Defaults to 16.
18
+ num_workers (int): The number of workers to use. Defaults to 1.
19
+ shuffle_before_split_by_node_buffer_size (Optional[int]): The buffer size for the shuffle before split by node. Defaults to 100.
20
+ shuffle_before_split_by_workers_buffer_size (Optional[int]): The buffer size for the shuffle before split by workers. Defaults to 100.
21
+ shuffle_before_filter_mappers_buffer_size (Optional[int]): The buffer size for the shuffle before filter mappers. Defaults to 1000.
22
+ shuffle_after_filter_mappers_buffer_size (Optional[int]): The buffer size for the shuffle after filter mappers. Defaults to 1000.
23
+ decoder (str): The decoder to use. Defaults to "pil".
24
+ handler (Callable): A callable to handle the warnings. Defaults to wds.warn_and_continue.
25
+ rename_files_fn (Optional[Callable[[str], str]]): A callable to rename the files. Defaults to None.
26
+ """
27
+
28
+ shards_path_or_urls: Union[str, List[str]] = None
29
+ per_worker_batch_size: int = 16
30
+ num_workers: int = 1
31
+ shuffle_before_split_by_node_buffer_size: Optional[int] = 100
32
+ shuffle_before_split_by_workers_buffer_size: Optional[int] = 100
33
+ shuffle_before_filter_mappers_buffer_size: Optional[int] = 1000
34
+ shuffle_after_filter_mappers_buffer_size: Optional[int] = 1000
35
+ decoder: str = "pil"
36
+ handler: Callable = wds.warn_and_continue
37
+ rename_files_fn: Optional[Callable[[str], str]] = None
38
+
39
+ def __post_init__(self):
40
+ super().__post_init__()
41
+ if self.rename_files_fn is not None:
42
+ assert callable(self.rename_files_fn), "rename_files must be a callable"
src/lbm/data/filters/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base import BaseFilter
2
+ from .filter_wrapper import FilterWrapper
3
+ from .filters import KeyFilter
4
+ from .filters_config import BaseFilterConfig, KeyFilterConfig
5
+
6
+ __all__ = [
7
+ "BaseFilter",
8
+ "FilterWrapper",
9
+ "KeyFilter",
10
+ "BaseFilterConfig",
11
+ "KeyFilterConfig",
12
+ ]
src/lbm/data/filters/base.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+
3
+ from .filters_config import BaseFilterConfig
4
+
5
+
6
+ class BaseFilter:
7
+ """
8
+ Base class for filters. This class should be subclassed to create a new filter.
9
+
10
+ Args:
11
+
12
+ config (BaseFilterConfig):
13
+ Configuration for the filter
14
+ """
15
+
16
+ def __init__(self, config: BaseFilterConfig):
17
+ self.verbose = config.verbose
18
+
19
+ def __call__(self, sample: Dict[str, Any]) -> bool:
20
+ """This function should be implemented by the subclass"""
21
+ raise NotImplementedError
src/lbm/data/filters/filter_wrapper.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Union
2
+
3
+ from .base import BaseFilter
4
+
5
+
6
+ class FilterWrapper:
7
+ """
8
+ Wrapper for multiple filters. This class allows to apply multiple filters to a batch of data.
9
+ The filters are applied in the order they are passed to the wrapper.
10
+
11
+ Args:
12
+
13
+ filters (List[BaseFilter]):
14
+ List of filters to apply to the batch of data
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ filters: Union[List[BaseFilter], None] = None,
20
+ ):
21
+ self.filters = filters
22
+
23
+ def __call__(self, batch: Dict[str, Any]) -> None:
24
+ """
25
+ Forward pass through all filters
26
+
27
+ Args:
28
+
29
+ batch: batch of data
30
+ """
31
+ filter_output = True
32
+ for filter in self.filters:
33
+ filter_output = filter(batch)
34
+ if not filter_output:
35
+ return False
36
+ return True
src/lbm/data/filters/filters.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from .base import BaseFilter
4
+ from .filters_config import KeyFilterConfig
5
+
6
+ logging.basicConfig(level=logging.INFO)
7
+
8
+
9
+ class KeyFilter(BaseFilter):
10
+ """
11
+ This filter checks if ALL the given keys are present in the sample
12
+
13
+ Args:
14
+
15
+ config (KeyFilterConfig): configuration for the filter
16
+ """
17
+
18
+ def __init__(self, config: KeyFilterConfig):
19
+ super().__init__(config)
20
+ keys = config.keys
21
+ if isinstance(keys, str):
22
+ keys = [keys]
23
+
24
+ self.keys = set(keys)
25
+
26
+ def __call__(self, batch: dict) -> bool:
27
+ try:
28
+ res = self.keys.issubset(set(batch.keys()))
29
+ return res
30
+ except Exception as e:
31
+ if self.verbose:
32
+ logging.error(f"Error in KeyFilter: {e}")
33
+ return False
src/lbm/data/filters/filters_config.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Union
2
+
3
+ from pydantic.dataclasses import dataclass
4
+
5
+ from ...config import BaseConfig
6
+
7
+
8
+ @dataclass
9
+ class BaseFilterConfig(BaseConfig):
10
+ """
11
+ Base configuration for filters
12
+
13
+ Args:
14
+
15
+ verbose (bool):
16
+ If True, print debug information. Defaults to False"""
17
+
18
+ verbose: bool = False
19
+
20
+
21
+ @dataclass
22
+ class KeyFilterConfig(BaseFilterConfig):
23
+ """
24
+ This filter checks if the keys are present in a sample.
25
+
26
+ Args:
27
+
28
+ keys (Union[str, List[str]]):
29
+ Key or list of keys to check. Defaults to "txt"
30
+ """
31
+
32
+ keys: Union[str, List[str]] = "txt"
src/lbm/data/mappers/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base import BaseMapper
2
+ from .mappers import KeyRenameMapper, RescaleMapper, TorchvisionMapper
3
+ from .mappers_config import (
4
+ KeyRenameMapperConfig,
5
+ RescaleMapperConfig,
6
+ TorchvisionMapperConfig,
7
+ )
8
+ from .mappers_wrapper import MapperWrapper
9
+
10
+ __all__ = [
11
+ "BaseMapper",
12
+ "KeyRenameMapper",
13
+ "RescaleMapper",
14
+ "TorchvisionMapper",
15
+ "KeyRenameMapperConfig",
16
+ "RescaleMapperConfig",
17
+ "TorchvisionMapperConfig",
18
+ "MapperWrapper",
19
+ ]
src/lbm/data/mappers/base.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+
3
+ from .mappers_config import BaseMapperConfig
4
+
5
+
6
+ class BaseMapper:
7
+ """
8
+ Base class for the mappers used to modify the samples in the data pipeline.
9
+
10
+ Args:
11
+
12
+ config (BaseMapperConfig):
13
+ Configuration for the mapper.
14
+ """
15
+
16
+ def __init__(self, config: BaseMapperConfig):
17
+ self.config = config
18
+ self.key = config.key
19
+
20
+ if config.output_key is None:
21
+ self.output_key = config.key
22
+ else:
23
+ self.output_key = config.output_key
24
+
25
+ def map(self, batch: Dict[str, Any], *args, **kwargs) -> Dict[str, Any]:
26
+ raise NotImplementedError
src/lbm/data/mappers/mappers.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+
3
+ from torchvision import transforms
4
+
5
+ from .base import BaseMapper
6
+ from .mappers_config import (
7
+ KeyRenameMapperConfig,
8
+ RescaleMapperConfig,
9
+ TorchvisionMapperConfig,
10
+ )
11
+
12
+
13
+ class KeyRenameMapper(BaseMapper):
14
+ """
15
+ Rename keys in a sample according to a key map
16
+
17
+ Args:
18
+
19
+ config (KeyRenameMapperConfig): Configuration for the mapper
20
+
21
+ Examples
22
+ ########
23
+
24
+ 1. Rename keys in a sample according to a key map
25
+
26
+ .. code-block:: python
27
+
28
+ from cr.data.mappers import KeyRenameMapper, KeyRenameMapperConfig
29
+
30
+ config = KeyRenameMapperConfig(
31
+ key_map={"old_key": "new_key"}
32
+ )
33
+
34
+ mapper = KeyRenameMapper(config)
35
+
36
+ sample = {"old_key": 1}
37
+ new_sample = mapper(sample)
38
+ print(new_sample) # {"new_key": 1}
39
+
40
+ 2. Rename keys in a sample according to a key map and a condition key
41
+
42
+ .. code-block:: python
43
+
44
+ from cr.data.mappers import KeyRenameMapper, KeyRenameMapperConfig
45
+
46
+ config = KeyRenameMapperConfig(
47
+ key_map={"old_key": "new_key"},
48
+ condition_key="condition",
49
+ condition_fn=lambda x: x == 1
50
+ )
51
+
52
+ mapper = KeyRenameMapper(config)
53
+
54
+ sample = {"old_key": 1, "condition": 1}
55
+ new_sample = mapper(sample)
56
+ print(new_sample) # {"new_key": 1}
57
+
58
+ sample = {"old_key": 1, "condition": 0}
59
+ new_sample = mapper(sample)
60
+ print(new_sample) # {"old_key": 1}
61
+
62
+ ```
63
+ """
64
+
65
+ def __init__(self, config: KeyRenameMapperConfig):
66
+ super().__init__(config)
67
+ self.key_map = config.key_map
68
+ self.condition_key = config.condition_key
69
+ self.condition_fn = config.condition_fn
70
+ self.else_key_map = config.else_key_map
71
+
72
+ def __call__(self, batch: Dict[str, Any], *args, **kwrags):
73
+ if self.condition_key is not None:
74
+ condition_key = batch[self.condition_key]
75
+ if self.condition_fn(condition_key):
76
+ for old_key, new_key in self.key_map.items():
77
+ if old_key in batch:
78
+ batch[new_key] = batch.pop(old_key)
79
+
80
+ elif self.else_key_map is not None:
81
+ for old_key, new_key in self.else_key_map.items():
82
+ if old_key in batch:
83
+ batch[new_key] = batch.pop(old_key)
84
+
85
+ else:
86
+ for old_key, new_key in self.key_map.items():
87
+ if old_key in batch:
88
+ batch[new_key] = batch.pop(old_key)
89
+ return batch
90
+
91
+
92
+ class TorchvisionMapper(BaseMapper):
93
+ """
94
+ Apply torchvision transforms to a sample
95
+
96
+ Args:
97
+
98
+ config (TorchvisionMapperConfig): Configuration for the mapper
99
+ """
100
+
101
+ def __init__(self, config: TorchvisionMapperConfig):
102
+ super().__init__(config)
103
+ chained_transforms = []
104
+ for transform, kwargs in zip(config.transforms, config.transforms_kwargs):
105
+ transform = getattr(transforms, transform)
106
+ chained_transforms.append(transform(**kwargs))
107
+ self.transforms = transforms.Compose(chained_transforms)
108
+
109
+ def __call__(self, batch: Dict[str, Any], *args, **kwrags) -> Dict[str, Any]:
110
+ if self.key in batch:
111
+ batch[self.output_key] = self.transforms(batch[self.key])
112
+ return batch
113
+
114
+
115
+ class RescaleMapper(BaseMapper):
116
+ """
117
+ Rescale a sample from [0, 1] to [-1, 1]
118
+
119
+ Args:
120
+
121
+ config (RescaleMapperConfig): Configuration for the mapper
122
+ """
123
+
124
+ def __init__(self, config: RescaleMapperConfig):
125
+ super().__init__(config)
126
+
127
+ def __call__(self, batch: Dict[str, Any], *args, **kwrags) -> Dict[str, Any]:
128
+ if isinstance(batch[self.key], list):
129
+ tmp = []
130
+ for i, image in enumerate(batch[self.key]):
131
+ tmp.append(2 * image - 1)
132
+ batch[self.output_key] = tmp
133
+ else:
134
+ batch[self.output_key] = 2 * batch[self.key] - 1
135
+ return batch
src/lbm/data/mappers/mappers_config.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional
2
+
3
+ from pydantic.dataclasses import dataclass
4
+
5
+ from ...config import BaseConfig
6
+
7
+
8
+ @dataclass
9
+ class BaseMapperConfig(BaseConfig):
10
+ """
11
+ Base configuration for mappers.
12
+
13
+ Args:
14
+
15
+ verbose (bool):
16
+ If True, print debug information. Defaults to False
17
+
18
+ key (Optional[str]):
19
+ Key to apply the mapper to. Defaults to None
20
+
21
+ output_key (Optional[str]):
22
+ Key to store the output of the mapper. Defaults to None
23
+ """
24
+
25
+ verbose: bool = False
26
+ key: Optional[str] = None
27
+ output_key: Optional[str] = None
28
+
29
+
30
+ @dataclass
31
+ class KeyRenameMapperConfig(BaseMapperConfig):
32
+ """
33
+ Rename keys in a sample according to a key map
34
+
35
+ Args:
36
+
37
+ key_map (Dict[str, str]): Dictionary with the old keys as keys and the new keys as values
38
+ condition_key (Optional[str]): Key to use for the condition. Defaults to None
39
+ condition_fn (Optional[Callable[[Any], bool]]): Function to use for the condition to be met so
40
+ the key map is applied. Defaults to None.
41
+ else_key_map (Optional[Dict[str, str]]): Dictionary with the old keys as keys and the new keys as values
42
+ if the condition is not met. Defaults to None *i.e.* the original key will be used.
43
+ """
44
+
45
+ key_map: Dict[str, str] = None
46
+ condition_key: Optional[str] = None
47
+ condition_fn: Optional[Callable[[Any], bool]] = None
48
+ else_key_map: Optional[Dict[str, str]] = None
49
+
50
+ def __post_init__(self):
51
+ super().__post_init__()
52
+ assert self.key_map is not None, "key_map should be provided"
53
+ assert all(
54
+ isinstance(old_key, str) and isinstance(new_key, str)
55
+ for old_key, new_key in self.key_map.items()
56
+ ), "key_map should be a dictionary with string keys and values"
57
+ if self.condition_key is not None:
58
+ assert self.condition_fn is not None, "condition_fn should be provided"
59
+ assert callable(self.condition_fn), "condition_fn should be callable"
60
+ if self.condition_fn is not None:
61
+ assert self.condition_key is not None, "condition_key should be provided"
62
+ assert isinstance(
63
+ self.condition_key, str
64
+ ), "condition_key should be a string"
65
+ if self.else_key_map is not None:
66
+ assert all(
67
+ isinstance(old_key, str) and isinstance(new_key, str)
68
+ for old_key, new_key in self.else_key_map.items()
69
+ ), "else_key_map should be a dictionary with string keys and values"
70
+
71
+
72
+ @dataclass
73
+ class TorchvisionMapperConfig(BaseMapperConfig):
74
+ """
75
+ Apply torchvision transforms to a sample
76
+
77
+ Args:
78
+
79
+ key (str): Key to apply the transforms to
80
+ transforms (torchvision.transforms): List of torchvision transforms to apply
81
+ transforms_kwargs (Dict[str, Any]): List of kwargs for the transforms
82
+ """
83
+
84
+ key: str = "image"
85
+ transforms: List[str] = None
86
+ transforms_kwargs: List[Dict[str, Any]] = None
87
+
88
+ def __post_init__(self):
89
+ super().__post_init__()
90
+ if self.transforms is None:
91
+ self.transforms = []
92
+ if self.transforms_kwargs is None:
93
+ self.transforms_kwargs = []
94
+ assert len(self.transforms) == len(
95
+ self.transforms_kwargs
96
+ ), "Number of transforms and kwargs should be same"
97
+
98
+
99
+ @dataclass
100
+ class RescaleMapperConfig(BaseMapperConfig):
101
+ """
102
+ Rescale a sample from [0, 1] to [-1, 1]
103
+
104
+ Args:
105
+
106
+ key (str): Key to rescale
107
+ """
108
+
109
+ key: str = "image"
src/lbm/data/mappers/mappers_wrapper.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Union
2
+
3
+ from .base import BaseMapper
4
+
5
+
6
+ class MapperWrapper:
7
+ """
8
+ Wrapper for the mappers to allow iterating over several mappers in one go.
9
+
10
+ Args:
11
+
12
+ mappers (Union[List[BaseMapper], None]): List of mappers to apply to the batch
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ mappers: Union[List[BaseMapper], None] = None,
18
+ ):
19
+ self.mappers = mappers
20
+
21
+ def __call__(self, batch: Dict[str, Any]) -> Dict[str, Any]:
22
+ """
23
+ Forward pass through all mappers
24
+
25
+ Args:
26
+
27
+ batch (Dict[str, Any]): batch of data
28
+ """
29
+ for mapper in self.mappers:
30
+ batch = mapper(batch)
31
+ return batch
src/lbm/inference/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .inference import evaluate
2
+ from .utils import get_model
3
+
4
+ __all__ = ["evaluate", "get_model"]
src/lbm/inference/inference.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ import PIL
4
+ import torch
5
+ from torchvision.transforms import ToPILImage, ToTensor
6
+
7
+ from lbm.models.lbm import LBMModel
8
+
9
+ logging.basicConfig(level=logging.INFO)
10
+ logger = logging.getLogger(__name__)
11
+
12
+ ASPECT_RATIOS = {
13
+ str(512 / 2048): (512, 2048),
14
+ str(1024 / 1024): (1024, 1024),
15
+ str(2048 / 512): (2048, 512),
16
+ str(896 / 1152): (896, 1152),
17
+ str(1152 / 896): (1152, 896),
18
+ str(512 / 1920): (512, 1920),
19
+ str(640 / 1536): (640, 1536),
20
+ str(768 / 1280): (768, 1280),
21
+ str(1280 / 768): (1280, 768),
22
+ str(1536 / 640): (1536, 640),
23
+ str(1920 / 512): (1920, 512),
24
+ }
25
+
26
+
27
+ @torch.no_grad()
28
+ def evaluate(
29
+ model: LBMModel,
30
+ source_image: PIL.Image.Image,
31
+ num_sampling_steps: int = 1,
32
+ ):
33
+ """
34
+ Evaluate the model on an image coming from the source distribution and generate a new image from the target distribution.
35
+
36
+ Args:
37
+ model (LBMModel): The model to evaluate.
38
+ source_image (PIL.Image.Image): The source image to evaluate the model on.
39
+ num_sampling_steps (int): The number of sampling steps to use for the model.
40
+
41
+ Returns:
42
+ PIL.Image.Image: The generated image.
43
+ """
44
+
45
+ ori_h_bg, ori_w_bg = source_image.size
46
+ ar_bg = ori_h_bg / ori_w_bg
47
+ closest_ar_bg = min(ASPECT_RATIOS, key=lambda x: abs(float(x) - ar_bg))
48
+ source_dimensions = ASPECT_RATIOS[closest_ar_bg]
49
+
50
+ source_image = source_image.resize(source_dimensions)
51
+
52
+ img_pasted_tensor = ToTensor()(source_image).unsqueeze(0) * 2 - 1
53
+ batch = {
54
+ "source_image": img_pasted_tensor.cuda().to(torch.bfloat16),
55
+ }
56
+
57
+ z_source = model.vae.encode(batch[model.source_key])
58
+
59
+ output_image = model.sample(
60
+ z=z_source,
61
+ num_steps=num_sampling_steps,
62
+ conditioner_inputs=batch,
63
+ max_samples=1,
64
+ ).clamp(-1, 1)
65
+
66
+ output_image = (output_image[0].float().cpu() + 1) / 2
67
+ output_image = ToPILImage()(output_image)
68
+ output_image.resize((ori_h_bg, ori_w_bg))
69
+
70
+ return output_image
src/lbm/inference/utils.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from typing import List, Optional
4
+
5
+ import torch
6
+ import yaml
7
+ from diffusers import FlowMatchEulerDiscreteScheduler
8
+ from huggingface_hub import snapshot_download
9
+ from safetensors.torch import load_file
10
+
11
+ from lbm.models.embedders import (
12
+ ConditionerWrapper,
13
+ LatentsConcatEmbedder,
14
+ LatentsConcatEmbedderConfig,
15
+ )
16
+ from lbm.models.lbm import LBMConfig, LBMModel
17
+ from lbm.models.unets import DiffusersUNet2DCondWrapper
18
+ from lbm.models.vae import AutoencoderKLDiffusers, AutoencoderKLDiffusersConfig
19
+
20
+
21
+ def get_model(
22
+ model_dir: str,
23
+ save_dir: Optional[str] = None,
24
+ torch_dtype: torch.dtype = torch.bfloat16,
25
+ device: str = "cuda",
26
+ ) -> LBMModel:
27
+ """Download the model from the model directory using either a local path or a path to HuggingFace Hub
28
+
29
+ Args:
30
+ model_dir (str): The path to the model directory containing the model weights and config, can be a local path or a path to HuggingFace Hub
31
+ save_dir (Optional[str]): The local path to save the model if downloading from HuggingFace Hub. Defaults to None.
32
+ torch_dtype (torch.dtype): The torch dtype to use for the model. Defaults to torch.bfloat16.
33
+ device (str): The device to use for the model. Defaults to "cuda".
34
+
35
+ Returns:
36
+ LBMModel: The loaded model
37
+ """
38
+ if not os.path.exists(model_dir):
39
+ local_dir = snapshot_download(
40
+ model_dir,
41
+ local_dir=save_dir,
42
+ )
43
+ model_dir = local_dir
44
+
45
+ model_files = os.listdir(model_dir)
46
+
47
+ # check yaml config file is present
48
+ yaml_file = [f for f in model_files if f.endswith(".yaml")]
49
+ if len(yaml_file) == 0:
50
+ raise ValueError("No yaml file found in the model directory.")
51
+
52
+ # check safetensors weights file is present
53
+ safetensors_files = sorted([f for f in model_files if f.endswith(".safetensors")])
54
+ ckpt_files = sorted([f for f in model_files if f.endswith(".ckpt")])
55
+ if len(safetensors_files) == 0 and len(ckpt_files) == 0:
56
+ raise ValueError("No safetensors or ckpt file found in the model directory")
57
+
58
+ if len(model_files) == 0:
59
+ raise ValueError("No model files found in the model directory")
60
+
61
+ with open(os.path.join(model_dir, yaml_file[0]), "r") as f:
62
+ config = yaml.safe_load(f)
63
+
64
+ model = _get_model_from_config(**config, torch_dtype=torch_dtype)
65
+
66
+ if len(safetensors_files) > 0:
67
+ logging.info(f"Loading safetensors file: {safetensors_files[-1]}")
68
+ sd = load_file(os.path.join(model_dir, safetensors_files[-1]))
69
+ model.load_state_dict(sd, strict=True)
70
+ elif len(ckpt_files) > 0:
71
+ logging.info(f"Loading ckpt file: {ckpt_files[-1]}")
72
+ sd = torch.load(
73
+ os.path.join(model_dir, ckpt_files[-1]),
74
+ map_location="cpu",
75
+ )["state_dict"]
76
+ sd = {k[6:]: v for k, v in sd.items() if k.startswith("model.")}
77
+ model.load_state_dict(
78
+ sd,
79
+ strict=True,
80
+ )
81
+ model.to(device).to(torch_dtype)
82
+
83
+ model.eval()
84
+
85
+ return model
86
+
87
+
88
+ def _get_model_from_config(
89
+ backbone_signature: str = "stabilityai/stable-diffusion-xl-base-1.0",
90
+ vae_num_channels: int = 4,
91
+ unet_input_channels: int = 4,
92
+ timestep_sampling: str = "log_normal",
93
+ selected_timesteps: Optional[List[float]] = None,
94
+ prob: Optional[List[float]] = None,
95
+ conditioning_images_keys: Optional[List[str]] = [],
96
+ conditioning_masks_keys: Optional[List[str]] = [],
97
+ source_key: str = "source_image",
98
+ target_key: str = "source_image_paste",
99
+ bridge_noise_sigma: float = 0.0,
100
+ logit_mean: float = 0.0,
101
+ logit_std: float = 1.0,
102
+ pixel_loss_type: str = "lpips",
103
+ latent_loss_type: str = "l2",
104
+ latent_loss_weight: float = 1.0,
105
+ pixel_loss_weight: float = 0.0,
106
+ torch_dtype: torch.dtype = torch.bfloat16,
107
+ **kwargs,
108
+ ):
109
+
110
+ conditioners = []
111
+
112
+ denoiser = DiffusersUNet2DCondWrapper(
113
+ in_channels=unet_input_channels, # Add downsampled_image
114
+ out_channels=vae_num_channels,
115
+ center_input_sample=False,
116
+ flip_sin_to_cos=True,
117
+ freq_shift=0,
118
+ down_block_types=[
119
+ "DownBlock2D",
120
+ "CrossAttnDownBlock2D",
121
+ "CrossAttnDownBlock2D",
122
+ ],
123
+ mid_block_type="UNetMidBlock2DCrossAttn",
124
+ up_block_types=["CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D"],
125
+ only_cross_attention=False,
126
+ block_out_channels=[320, 640, 1280],
127
+ layers_per_block=2,
128
+ downsample_padding=1,
129
+ mid_block_scale_factor=1,
130
+ dropout=0.0,
131
+ act_fn="silu",
132
+ norm_num_groups=32,
133
+ norm_eps=1e-05,
134
+ cross_attention_dim=[320, 640, 1280],
135
+ transformer_layers_per_block=[1, 2, 10],
136
+ reverse_transformer_layers_per_block=None,
137
+ encoder_hid_dim=None,
138
+ encoder_hid_dim_type=None,
139
+ attention_head_dim=[5, 10, 20],
140
+ num_attention_heads=None,
141
+ dual_cross_attention=False,
142
+ use_linear_projection=True,
143
+ class_embed_type=None,
144
+ addition_embed_type=None,
145
+ addition_time_embed_dim=None,
146
+ num_class_embeds=None,
147
+ upcast_attention=None,
148
+ resnet_time_scale_shift="default",
149
+ resnet_skip_time_act=False,
150
+ resnet_out_scale_factor=1.0,
151
+ time_embedding_type="positional",
152
+ time_embedding_dim=None,
153
+ time_embedding_act_fn=None,
154
+ timestep_post_act=None,
155
+ time_cond_proj_dim=None,
156
+ conv_in_kernel=3,
157
+ conv_out_kernel=3,
158
+ projection_class_embeddings_input_dim=None,
159
+ attention_type="default",
160
+ class_embeddings_concat=False,
161
+ mid_block_only_cross_attention=None,
162
+ cross_attention_norm=None,
163
+ addition_embed_type_num_heads=64,
164
+ ).to(torch_dtype)
165
+
166
+ if conditioning_images_keys != [] or conditioning_masks_keys != []:
167
+
168
+ latents_concat_embedder_config = LatentsConcatEmbedderConfig(
169
+ image_keys=conditioning_images_keys,
170
+ mask_keys=conditioning_masks_keys,
171
+ )
172
+ latent_concat_embedder = LatentsConcatEmbedder(latents_concat_embedder_config)
173
+ latent_concat_embedder.freeze()
174
+ conditioners.append(latent_concat_embedder)
175
+
176
+ # Wrap conditioners and set to device
177
+ conditioner = ConditionerWrapper(
178
+ conditioners=conditioners,
179
+ )
180
+
181
+ ## VAE ##
182
+ # Get VAE model
183
+ vae_config = AutoencoderKLDiffusersConfig(
184
+ version=backbone_signature,
185
+ subfolder="vae",
186
+ tiling_size=(128, 128),
187
+ )
188
+ vae = AutoencoderKLDiffusers(vae_config).to(torch_dtype)
189
+ vae.freeze()
190
+ vae.to(torch_dtype)
191
+
192
+ ## Diffusion Model ##
193
+ # Get diffusion model
194
+ config = LBMConfig(
195
+ source_key=source_key,
196
+ target_key=target_key,
197
+ latent_loss_weight=latent_loss_weight,
198
+ latent_loss_type=latent_loss_type,
199
+ pixel_loss_type=pixel_loss_type,
200
+ pixel_loss_weight=pixel_loss_weight,
201
+ timestep_sampling=timestep_sampling,
202
+ logit_mean=logit_mean,
203
+ logit_std=logit_std,
204
+ selected_timesteps=selected_timesteps,
205
+ prob=prob,
206
+ bridge_noise_sigma=bridge_noise_sigma,
207
+ )
208
+
209
+ sampling_noise_scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
210
+ backbone_signature,
211
+ subfolder="scheduler",
212
+ )
213
+
214
+ model = LBMModel(
215
+ config,
216
+ denoiser=denoiser,
217
+ sampling_noise_scheduler=sampling_noise_scheduler,
218
+ vae=vae,
219
+ conditioner=conditioner,
220
+ ).to(torch_dtype)
221
+
222
+ return model
src/lbm/models/__init__.py ADDED
File without changes
src/lbm/models/base/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .base_model import BaseModel
2
+ from .model_config import ModelConfig
3
+
4
+ __all__ = ["BaseModel", "ModelConfig"]
src/lbm/models/base/base_model.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ from .model_config import ModelConfig
7
+
8
+
9
+ class BaseModel(nn.Module):
10
+ def __init__(self, config: ModelConfig):
11
+ nn.Module.__init__(self)
12
+ self.config = config
13
+ self.input_key = config.input_key
14
+ self.device = torch.device("cpu")
15
+ self.dtype = torch.float32
16
+
17
+ def on_fit_start(self, device: torch.device | None = None, *args, **kwargs):
18
+ """Called when the training starts
19
+
20
+ Args:
21
+ device (Optional[torch.device], optional): The device to use. Usefull to set
22
+ relevant parameters on the model and embedder to the right device only
23
+ once at the start of the training. Defaults to None.
24
+ """
25
+ if device is not None:
26
+ self.device = device
27
+ self.to(self.device)
28
+
29
+ def forward(self, batch: Dict[str, Any], *args, **kwargs):
30
+ raise NotImplementedError("forward method is not implemented")
31
+
32
+ def freeze(self):
33
+ """Freeze the model"""
34
+ self.eval()
35
+ for param in self.parameters():
36
+ param.requires_grad = False
37
+
38
+ def to(self, *args, **kwargs):
39
+ device, dtype, non_blocking, _ = torch._C._nn._parse_to(*args, **kwargs)
40
+ self = super().to(
41
+ device=device,
42
+ dtype=dtype,
43
+ non_blocking=non_blocking,
44
+ )
45
+
46
+ if device is not None:
47
+ self.device = device
48
+ if dtype is not None:
49
+ self.dtype = dtype
50
+ return self
51
+
52
+ def compute_metrics(self, batch: Dict[str, Any], *args, **kwargs):
53
+ """Compute the metrics"""
54
+ return {}
55
+
56
+ def sample(self, batch: Dict[str, Any], *args, **kwargs):
57
+ """Sample from the model"""
58
+ return {}
59
+
60
+ def log_samples(self, batch: Dict[str, Any], *args, **kwargs):
61
+ """Log the samples"""
62
+ return None
63
+
64
+ def on_train_batch_end(self, batch: Dict[str, Any], *args, **kwargs):
65
+ """Update the model an optimization is perforned on a batch."""
66
+ pass
src/lbm/models/base/model_config.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from pydantic.dataclasses import dataclass
2
+
3
+ from ...config import BaseConfig
4
+
5
+
6
+ @dataclass
7
+ class ModelConfig(BaseConfig):
8
+ input_key: str = "image"
src/lbm/models/embedders/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .conditioners_wrapper import ConditionerWrapper
2
+ from .latents_concat import LatentsConcatEmbedder, LatentsConcatEmbedderConfig
3
+
4
+ __all__ = ["LatentsConcatEmbedder", "LatentsConcatEmbedderConfig", "ConditionerWrapper"]
src/lbm/models/embedders/base/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .base_conditioner import BaseConditioner
2
+ from .base_conditioner_config import BaseConditionerConfig
3
+
4
+ __all__ = ["BaseConditioner", "BaseConditionerConfig"]
src/lbm/models/embedders/base/base_conditioner.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Union
2
+
3
+ import torch
4
+
5
+ from ...base.base_model import BaseModel
6
+ from .base_conditioner_config import BaseConditionerConfig
7
+
8
+ DIM2CONDITIONING = {
9
+ 2: "vector",
10
+ 3: "crossattn",
11
+ 4: "concat",
12
+ }
13
+
14
+
15
+ class BaseConditioner(BaseModel):
16
+ """This is the base class for all the conditioners. This absctacts the conditioning process
17
+
18
+ Args:
19
+
20
+ config (BaseConditionerConfig): The configuration of the conditioner
21
+
22
+ Examples
23
+ ########
24
+
25
+ To use the conditioner, you can import the class and use it as follows:
26
+
27
+ .. code-block:: python
28
+
29
+ from cr.models.embedders import BaseConditioner, BaseConditionerConfig
30
+
31
+ # Create the conditioner config
32
+ config = BaseConditionerConfig(
33
+ input_key="text", # The key for the input
34
+ unconditional_conditioning_rate=0.3, # Drops the conditioning with 30% probability during training
35
+ )
36
+
37
+ # Create the conditioner
38
+ conditioner = BaseConditioner(config)
39
+ """
40
+
41
+ def __init__(self, config: BaseConditionerConfig):
42
+ BaseModel.__init__(self, config)
43
+ self.config = config
44
+ self.input_key = config.input_key
45
+ self.dim2outputkey = DIM2CONDITIONING
46
+ self.ucg_rate = config.unconditional_conditioning_rate
47
+
48
+ def forward(
49
+ self, batch: Dict[str, Any], force_zero_embedding: bool = False, *args, **kwargs
50
+ ):
51
+ """
52
+ Forward pass of the embedder.
53
+
54
+ Args:
55
+
56
+ batch (Dict[str, Any]): A dictionary containing the input data.
57
+ force_zero_embedding (bool): Whether to force zero embedding.
58
+ This will return an embedding with all entries set to 0. Defaults to False.
59
+ """
60
+ raise NotImplementedError("Forward pass must be implemented in child class")
src/lbm/models/embedders/base/base_conditioner_config.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+
3
+ from pydantic.dataclasses import dataclass
4
+
5
+ from ....config import BaseConfig
6
+
7
+
8
+ @dataclass
9
+ class BaseConditionerConfig(BaseConfig):
10
+ """This is the ClipEmbedderConfig class which defines all the useful parameters to instantiate the model
11
+
12
+ Args:
13
+
14
+ input_key (str): The key for the input. Defaults to "text".
15
+ unconditional_conditioning_rate (float): Drops the conditioning with this probability during training. Defaults to 0.0.
16
+ """
17
+
18
+ input_key: str = "text"
19
+ unconditional_conditioning_rate: float = 0.0
20
+
21
+ def __post_init__(self):
22
+ super().__post_init__()
23
+
24
+ assert (
25
+ self.unconditional_conditioning_rate >= 0.0
26
+ and self.unconditional_conditioning_rate <= 1.0
27
+ ), "Unconditional conditioning rate should be between 0 and 1"