diff --git a/sdk/python/feast/feature_server.py b/sdk/python/feast/feature_server.py
index 0502c2a85d..5fc8129ad8 100644
--- a/sdk/python/feast/feature_server.py
+++ b/sdk/python/feast/feature_server.py
@@ -1,10 +1,9 @@
-import json
 import sys
 import threading
 import time
 import traceback
 from contextlib import asynccontextmanager
-from typing import List, Optional
+from typing import Any, Dict, List, Optional

 import pandas as pd
 import psutil
@@ -69,6 +68,13 @@ class MaterializeIncrementalRequest(BaseModel):
     feature_views: Optional[List[str]] = None

+class GetOnlineFeaturesRequest(BaseModel):
+    entities: Dict[str, List[Any]]
+    feature_service: Optional[str] = None
+    features: Optional[List[str]] = None
+    full_feature_names: bool = False
+
+
 def get_app(
     store: "feast.FeatureStore",
     registry_ttl_sec: int = DEFAULT_FEATURE_SERVER_REGISTRY_TTL,
@@ -108,33 +114,26 @@ async def lifespan(app: FastAPI):

     app = FastAPI(lifespan=lifespan)

-    async def get_body(request: Request):
-        return await request.body()
-
     @app.post(
         "/get-online-features",
         dependencies=[Depends(inject_user_details)],
     )
-    async def get_online_features(body=Depends(get_body)):
-        body = json.loads(body)
-        full_feature_names = body.get("full_feature_names", False)
-        entity_rows = body["entities"]
+    async def get_online_features(request: GetOnlineFeaturesRequest) -> Dict[str, Any]:
         # Initialize parameters for FeatureStore.get_online_features(...) call
-        if "feature_service" in body:
+        if request.feature_service:
             feature_service = store.get_feature_service(
-                body["feature_service"], allow_cache=True
+                request.feature_service, allow_cache=True
             )
             assert_permissions(
                 resource=feature_service, actions=[AuthzedAction.READ_ONLINE]
             )
-            features = feature_service
+            features = feature_service  # type: ignore
         else:
-            features = body["features"]
             all_feature_views, all_on_demand_feature_views = (
                 utils._get_feature_views_to_use(
                     store.registry,
                     store.project,
-                    features,
+                    request.features,
                     allow_cache=True,
                     hide_dummy_entity=False,
                 )
@@ -147,18 +146,19 @@ async def get_online_features(body=Depends(get_body)):
                 assert_permissions(
                     resource=od_feature_view, actions=[AuthzedAction.READ_ONLINE]
                 )
+            features = request.features  # type: ignore

         read_params = dict(
             features=features,
-            entity_rows=entity_rows,
-            full_feature_names=full_feature_names,
+            entity_rows=request.entities,
+            full_feature_names=request.full_feature_names,
         )

         if store._get_provider().async_supported.online.read:
-            response = await store.get_online_features_async(**read_params)
+            response = await store.get_online_features_async(**read_params)  # type: ignore
         else:
             response = await run_in_threadpool(
-                lambda: store.get_online_features(**read_params)
+                lambda: store.get_online_features(**read_params)  # type: ignore
             )

         # Convert the Protobuf object to JSON and return it
@@ -167,8 +167,7 @@ async def get_online_features(body=Depends(get_body)):
         )

     @app.post("/push", dependencies=[Depends(inject_user_details)])
-    async def push(body=Depends(get_body)):
-        request = PushFeaturesRequest(**json.loads(body))
+    async def push(request: PushFeaturesRequest) -> None:
         df = pd.DataFrame(request.df)
         actions = []
         if request.to == "offline":
@@ -220,17 +219,16 @@ async def push(body=Depends(get_body)):
             store.push(**push_params)

     @app.post("/write-to-online-store", dependencies=[Depends(inject_user_details)])
-    def write_to_online_store(body=Depends(get_body)):
-        request = WriteToFeatureStoreRequest(**json.loads(body))
+    def write_to_online_store(request: WriteToFeatureStoreRequest) -> None:
         df = pd.DataFrame(request.df)
         feature_view_name = request.feature_view_name
         allow_registry_cache = request.allow_registry_cache
         try:
-            feature_view = store.get_stream_feature_view(
+            feature_view = store.get_stream_feature_view(  # type: ignore
                 feature_view_name, allow_registry_cache=allow_registry_cache
             )
         except FeatureViewNotFoundException:
-            feature_view = store.get_feature_view(
+            feature_view = store.get_feature_view(  # type: ignore
                 feature_view_name, allow_registry_cache=allow_registry_cache
             )

@@ -250,11 +248,12 @@ async def health():
         )

     @app.post("/materialize", dependencies=[Depends(inject_user_details)])
-    def materialize(body=Depends(get_body)):
-        request = MaterializeRequest(**json.loads(body))
-        for feature_view in request.feature_views:
+    def materialize(request: MaterializeRequest) -> None:
+        for feature_view in request.feature_views or []:
+            # TODO: receives a str for resource but isn't in the Union. is str actually allowed?
             assert_permissions(
-                resource=feature_view, actions=[AuthzedAction.WRITE_ONLINE]
+                resource=feature_view,  # type: ignore
+                actions=[AuthzedAction.WRITE_ONLINE],
             )
         store.materialize(
             utils.make_tzaware(parser.parse(request.start_ts)),
@@ -263,11 +262,12 @@ def materialize(body=Depends(get_body)):
         )

     @app.post("/materialize-incremental", dependencies=[Depends(inject_user_details)])
-    def materialize_incremental(body=Depends(get_body)):
-        request = MaterializeIncrementalRequest(**json.loads(body))
-        for feature_view in request.feature_views:
+    def materialize_incremental(request: MaterializeIncrementalRequest) -> None:
+        for feature_view in request.feature_views or []:
+            # TODO: receives a str for resource but isn't in the Union. is str actually allowed?
             assert_permissions(
-                resource=feature_view, actions=[AuthzedAction.WRITE_ONLINE]
+                resource=feature_view,  # type: ignore
+                actions=[AuthzedAction.WRITE_ONLINE],
             )
         store.materialize_incremental(
             utils.make_tzaware(parser.parse(request.end_ts)), request.feature_views

Addition of /docs endpoint
Creation of /docs endpoint in order to have a place to view easily all the avilable endpoints with:

- a basic endpoint description.
- its development status/maturity
- requiered and optional parameters
- example of request body
- example of a succesful response
- custem errors explanation(if exist)


diff --git a/django/urls/base.py b/django/urls/base.py
index 753779c75b46..bb40ba222436 100644
--- a/django/urls/base.py
+++ b/django/urls/base.py
@@ -127,8 +127,9 @@ def clear_script_prefix():

 def set_urlconf(urlconf_name):
     """
-    Set the URLconf for the current thread (overriding the default one in
-    settings). If urlconf_name is None, revert back to the default.
+    Set the URLconf for the current thread or asyncio task (overriding the
+    default one in settings). If urlconf_name is None, revert back to the
+    default.
     """
     if urlconf_name:
         _urlconfs.value = urlconf_name
@@ -139,8 +140,8 @@ def set_urlconf(urlconf_name):

 def get_urlconf(default=None):
     """
-    Return the root URLconf to use for the current thread if it has been
-    changed from the default one.
+    Return the root URLconf to use for the current thread or asyncio task if it
+    has been changed from the default one.
     """
     return getattr(_urlconfs, "value", default)

Clarify django.urls.set_urlconf scoping behaviour
Description

django.urls.set_urlconf docstring mentions setting the urlconf for the current thread. However, this is backed by asgiref.local.Local, which is supposed to provide scoping features related to asyncio tasks as well. This becomes relevant, for example, when doing multi-tenancy with more than one urlconf and trying to call django.urls.reverse in an ASGI application.
I have been trying to infer what is the expected behaviour in async Django code by following the current implementation, and I found that asgiref.local.Local behaviour has changed over time (see https://github.com/django/asgiref/issues/473).
I assume that using asgiref.local.Local instead of threading.local hints at an intention is to give set_urlconf/get_urlconf meaningful semantics for Channels consumers or ASGI applications.
Whether the intention is to isolate set_urlconf/get_urlconf across different asyncio tasks or to only support isolation between threads, I suppose it would be useful if their behaviour was documented also for the case of asyncio code, especially given they back django.urls.reverse.

["I'm struggling to follow what this is asking for - can you share an example of the behavior you're seeing? From what I can see, both async and sync requests handle the urlconf the same - it is the ROOT_URLCONF unless set by a middleware \u200bas documented.", 1728267595.0]
["Firstly, just for Django, set_urlconf is not public API so you shouldn't use it. Rather prefer the documented HttpRequest.urlconf attribute (\u200bdocs) to set per-tenant URLs in a middleware, if that's your strategy. Secondly, the \u200blinked asgiref issue (#473) is in progress, and should be resolved shortly. (Setting locals has been leaking out of asyncio tasks since the recent v3.8, which is a regression. You can pin to v3.7.2 pending the next release.) It's not a Django issue. If you need further advice please see TicketClosingReasons/UseSupportChannels.", 1728268240.0]
['From what I could see, "Set the URLconf for the current thread" in set_urlconf\'s docstring looks like a leftover from the pre-async times and could become "Set the URLconf for the current thread or asyncio task". I understand it\'s not a public API and indeed I only set request.urlconf in my code. We spotted the docstring while trying to double check the validity of what we were designing on the async case, and had some extra digging to do to reassure ourselves we were still doing the right thing, hence this issue. I\'m surprised the ticket got closed, but fair enough.', 1728269648.0]
['Yes, OK, just changing the docstring would be fine.', 1728270267.0]
['\u200bPR', 1728270548.0]
['In d876be79: Fixed #35807 -- Mentioned async case for internal get/set urlconf helpers.', 1728274635.0]


diff --git a/src/diffusers/training_utils.py b/src/diffusers/training_utils.py
index d2bf3fe07185..2474ed5c2114 100644
--- a/src/diffusers/training_utils.py
+++ b/src/diffusers/training_utils.py
@@ -43,6 +43,9 @@ def set_seed(seed: int):

     Args:
         seed (`int`): The seed to set.
+
+    Returns:
+        `None`
     """
     random.seed(seed)
     np.random.seed(seed)
@@ -58,6 +61,17 @@ def compute_snr(noise_scheduler, timesteps):
     """
     Computes SNR as per
     https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
+    for the given timesteps using the provided noise scheduler.
+
+    Args:
+        noise_scheduler (`NoiseScheduler`):
+            An object containing the noise schedule parameters, specifically `alphas_cumprod`, which is used to compute
+            the SNR values.
+        timesteps (`torch.Tensor`):
+            A tensor of timesteps for which the SNR is computed.
+
+    Returns:
+        `torch.Tensor`: A tensor containing the computed SNR values for each timestep.
     """
     alphas_cumprod = noise_scheduler.alphas_cumprod
     sqrt_alphas_cumprod = alphas_cumprod**0.5

[community] Improving docstrings and type hints
There are many instances in the codebase where our docstring/typing convention is not followed. We'd like to work on improving this with your help!

Our convention looks like:

```python3
def function_name(parameter_1: Union[str, List[str]], parameter_2: Optional[int] = None, parameter_3: float = 42.0) -> Civilization:
    r"""
    Function that creates a simulation.

    Args:
        parameter_1 (`str` or `List[str]`):
            Description of game level.
        parameter_2 (`int`, *optional*):
            Kardashev scale of civilization.
        parameter_3 (`float`, defaults to `42.0`):
            Difficulty scale.

    Returns:
        [`~simulations.objects.Civilization`]
            A civilization simulation with provided initialization parameters.
    """
```

Some examples that don't follow the docstring convention are:
- [this](https://github.com/huggingface/diffusers/blob/c4a8979f3018fbffee33304c1940561f7a5cf613/src/diffusers/models/embeddings.py#L89): missing explanations
- [this](https://github.com/huggingface/diffusers/blob/33fafe3d143ca8380a9e405e7acfa69091d863fb/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L132): does not contain mixin-related documentation whereas as [this](https://github.com/huggingface/diffusers/blob/33fafe3d143ca8380a9e405e7acfa69091d863fb/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py#L154) does
- [this](https://github.com/huggingface/diffusers/blob/c4a8979f3018fbffee33304c1940561f7a5cf613/src/diffusers/utils/import_utils.py#L672): function explanation after "Args", but should be before
- [this](https://github.com/huggingface/diffusers/blob/c4a8979f3018fbffee33304c1940561f7a5cf613/src/diffusers/pipelines/deepfloyd_if/pipeline_output.py#L14): same reason as above
- [this](https://github.com/huggingface/diffusers/blob/c4a8979f3018fbffee33304c1940561f7a5cf613/src/diffusers/models/embeddings.py#L518): incorrect indentation

There are also many places where docstrings are completely missing or inadequately explained. If you feel something needs an improvement, you can open a PR with your suggestions too! Additionally, type hints are not appropriate/correctly used at many occurrences and mismatch the accompanying docstrings - these could use an improvement too!

Please limit your PRs to changes to a single file in each PR. Changes must be only related to docstrings/type hints. Feel free to ping either @yiyixuxu, @stevhliu or me for reviews.

Hi @a-r-r-o-w I'd like to take this up, please let me know if there are any other prerequisites I should be aware of before submitting a PR against this issue 🙂
Not prerequisites I can think of off the top of my head. Just that the PRs should be limited in scope as mentioned. You can maybe look at the Diffusers contribution guide (and philosophy, if you're interested)
I'll take up some of these.
I’m also interested in this work. Could you let me know about the current progress? @SubhasmitaSw @charchit7
Hey @yijun-lee, I've been caught up with some work, unfortunately, but I’ll work on this over the weekend or later today. If you want to get started on any of these tasks, feel free to go ahead and let us know, so we can pick up whatever is left.
Oh, actually, I think I’ll be starting this weekend as well. If we proceed separately, it would be good to inform each other through comments or other means. Have a good day :) @charchit7
Sure, @yijun-lee, that works!
you too :)
Hello there guys, I'd also like to contribute in this issue. I'm sorry I didn't really drop in a message here yet but I hope this PR helps push things forward! A g'day to all.
Feel free to take up as many files as you want (one file per PR however)! The ones mentioned in the issue description are just a few examples, but there are probably hundreds of files that could use improvements. Please keep them coming, thanks
Hello! I'm also following this issue with interest. I’ve submitted my first PR, so please let me know if there are any mistakes! Have a great day!
Hello! Thanks for holding interesting issue! I'm fully circled for this new work ! 🙆🏻♀  🙆🏻♀
I also have opened my PR, please let me know if I missed something !

+ Q. which should I prioritize modern python docstring conventions or unity of that file (e.g. expression) ?
@a-r-r-o-w hi, i wank to work on it

Hello colleagues,
I'm also interested into this issues. I made a first PR related to this issue.
Since there are lots of docstrings to update, I'm also interested into list up missing docstring files if I have time :)
Thank you in advance for your time and guidance!
Hello everyone! 😊
I'm also interested in this issue and have made some updates to the docstrings in `src/diffusers/training_utils.py`. I would love to get your feedback on my changes!

I’m excited to contribute and be part of this discussion. Thank you in advance for your time and guidance 🤗

Hi I would love to be of help here.
I have made some additions to the docstrings in src/diffusers/training_utils.py.
Would love to get your feedback on the PR :)


diff --git a/src/diffusers/training_utils.py b/src/diffusers/training_utils.py
index 57bd9074870c..11a4e1cc8069 100644
--- a/src/diffusers/training_utils.py
+++ b/src/diffusers/training_utils.py
@@ -36,8 +36,9 @@

 def set_seed(seed: int):
     """
-    Args:
     Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch`.
+
+    Args:
         seed (`int`): The seed to set.
     """
     random.seed(seed)
@@ -194,6 +195,13 @@ def unet_lora_state_dict(unet: UNet2DConditionModel) -> Dict[str, torch.Tensor]:

 def cast_training_params(model: Union[torch.nn.Module, List[torch.nn.Module]], dtype=torch.float32):
+    """
+    Casts the training parameters of the model to the specified data type.
+
+    Args:
+        model: The PyTorch model whose parameters will be cast.
+        dtype: The data type to which the model parameters will be cast.
+    """
     if not isinstance(model, list):
         model = [model]
     for m in model:
@@ -225,7 +233,8 @@ def _set_state_dict_into_text_encoder(
 def compute_density_for_timestep_sampling(
     weighting_scheme: str, batch_size: int, logit_mean: float = None, logit_std: float = None, mode_scale: float = None
 ):
-    """Compute the density for sampling the timesteps when doing SD3 training.
+    """
+    Compute the density for sampling the timesteps when doing SD3 training.

     Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.

@@ -244,7 +253,8 @@ def compute_density_for_timestep_sampling(

 def compute_loss_weighting_for_sd3(weighting_scheme: str, sigmas=None):
-    """Computes loss weighting scheme for SD3 training.
+    """
+    Computes loss weighting scheme for SD3 training.

     Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.

@@ -261,7 +271,9 @@ def compute_loss_weighting_for_sd3(weighting_scheme: str, sigmas=None):

 def free_memory():
-    """Runs garbage collection. Then clears the cache of the available accelerator."""
+    """
+    Runs garbage collection. Then clears the cache of the available accelerator.
+    """
     gc.collect()

     if torch.cuda.is_available():
@@ -494,7 +506,8 @@ def pin_memory(self) -> None:
         self.shadow_params = [p.pin_memory() for p in self.shadow_params]

     def to(self, device=None, dtype=None, non_blocking=False) -> None:
-        r"""Move internal buffers of the ExponentialMovingAverage to `device`.
+        r"""
+        Move internal buffers of the ExponentialMovingAverage to `device`.

         Args:
             device: like `device` argument to `torch.Tensor.to`
@@ -528,23 +541,25 @@ def state_dict(self) -> dict:

     def store(self, parameters: Iterable[torch.nn.Parameter]) -> None:
         r"""
+        Saves the current parameters for restoring later.
+
         Args:
-        Save the current parameters for restoring later.
-            parameters: Iterable of `torch.nn.Parameter`; the parameters to be
-                temporarily stored.
+            parameters: Iterable of `torch.nn.Parameter`. The parameters to be temporarily stored.
         """
         self.temp_stored_params = [param.detach().cpu().clone() for param in parameters]

     def restore(self, parameters: Iterable[torch.nn.Parameter]) -> None:
         r"""
-        Args:
-        Restore the parameters stored with the `store` method. Useful to validate the model with EMA parameters without:
-        affecting the original optimization process. Store the parameters before the `copy_to()` method. After
+        Restore the parameters stored with the `store` method. Useful to validate the model with EMA parameters
+        without: affecting the original optimization process. Store the parameters before the `copy_to()` method. After
         validation (or model saving), use this to restore the former parameters.
+
+        Args:
             parameters: Iterable of `torch.nn.Parameter`; the parameters to be
                 updated with the stored parameters. If `None`, the parameters with which this
                 `ExponentialMovingAverage` was initialized will be used.
         """
+
         if self.temp_stored_params is None:
             raise RuntimeError("This ExponentialMovingAverage has no `store()`ed weights " "to `restore()`")
         if self.foreach:
@@ -560,9 +575,10 @@ def restore(self, parameters: Iterable[torch.nn.Parameter]) -> None:

     def load_state_dict(self, state_dict: dict) -> None:
         r"""
-        Args:
         Loads the ExponentialMovingAverage state. This method is used by accelerate during checkpointing to save the
         ema state dict.
+
+        Args:
             state_dict (dict): EMA state. Should be an object returned
                 from a call to :meth:`state_dict`.
         """

Hi @a-r-r-o-w I'd like to take this up, please let me know if there are any other prerequisites I should be aware of before submitting a PR against this issue 🙂
Not prerequisites I can think of off the top of my head. Just that the PRs should be limited in scope as mentioned. You can maybe look at the Diffusers contribution guide (and philosophy, if you're interested)
I'll take up some of these.
I’m also interested in this work. Could you let me know about the current progress? @SubhasmitaSw @charchit7
Hey @yijun-lee, I've been caught up with some work, unfortunately, but I’ll work on this over the weekend or later today. If you want to get started on any of these tasks, feel free to go ahead and let us know, so we can pick up whatever is left.
Oh, actually, I think I’ll be starting this weekend as well. If we proceed separately, it would be good to inform each other through comments or other means. Have a good day :) @charchit7
Sure, @yijun-lee, that works!
you too :)
Hello there guys, I'd also like to contribute in this issue. I'm sorry I didn't really drop in a message here yet but I hope this PR helps push things forward! A g'day to all.
Feel free to take up as many files as you want (one file per PR however)! The ones mentioned in the issue description are just a few examples, but there are probably hundreds of files that could use improvements. Please keep them coming, thanks
Hello! I'm also following this issue with interest. I’ve submitted my first PR, so please let me know if there are any mistakes! Have a great day!
Hello! Thanks for holding interesting issue! I'm fully circled for this new work ! 🙆🏻♀  🙆🏻♀
I also have opened my PR, please let me know if I missed something !

+ Q. which should I prioritize modern python docstring conventions or unity of that file (e.g. expression) ?
@a-r-r-o-w hi, i wank to work on it

Hello colleagues,
I'm also interested into this issues. I made a first PR related to this issue.
Since there are lots of docstrings to update, I'm also interested into list up missing docstring files if I have time :)
Thank you in advance for your time and guidance!


diff --git a/src/diffusers/utils/import_utils.py b/src/diffusers/utils/import_utils.py
index 34cc5fcc8605..daecec4aa258 100644
--- a/src/diffusers/utils/import_utils.py
+++ b/src/diffusers/utils/import_utils.py
@@ -668,8 +668,9 @@ def __getattr__(cls, key):
 # This function was copied from: https://github.com/huggingface/accelerate/blob/874c4967d94badd24f893064cc3bef45f57cadf7/src/accelerate/utils/versions.py#L319
 def compare_versions(library_or_version: Union[str, Version], operation: str, requirement_version: str):
     """
-    Args:
     Compares a library version to some requirement using a given operation.
+
+    Args:
         library_or_version (`str` or `packaging.version.Version`):
             A library name or a version to check.
         operation (`str`):
@@ -688,8 +689,9 @@ def compare_versions(library_or_version: Union[str, Version], operation: str, re
 # This function was copied from: https://github.com/huggingface/accelerate/blob/874c4967d94badd24f893064cc3bef45f57cadf7/src/accelerate/utils/versions.py#L338
 def is_torch_version(operation: str, version: str):
     """
-    Args:
     Compares the current PyTorch version to a given reference with an operation.
+
+    Args:
         operation (`str`):
             A string representation of an operator, such as `">"` or `"<="`
         version (`str`):
@@ -700,8 +702,9 @@ def is_torch_version(operation: str, version: str):

 def is_transformers_version(operation: str, version: str):
     """
-    Args:
     Compares the current Transformers version to a given reference with an operation.
+
+    Args:
         operation (`str`):
             A string representation of an operator, such as `">"` or `"<="`
         version (`str`):
@@ -714,8 +717,9 @@ def is_transformers_version(operation: str, version: str):

 def is_accelerate_version(operation: str, version: str):
     """
-    Args:
     Compares the current Accelerate version to a given reference with an operation.
+
+    Args:
         operation (`str`):
             A string representation of an operator, such as `">"` or `"<="`
         version (`str`):
@@ -728,8 +732,9 @@ def is_accelerate_version(operation: str, version: str):

 def is_peft_version(operation: str, version: str):
     """
-    Args:
     Compares the current PEFT version to a given reference with an operation.
+
+    Args:
         operation (`str`):
             A string representation of an operator, such as `">"` or `"<="`
         version (`str`):
@@ -742,8 +747,9 @@ def is_peft_version(operation: str, version: str):

 def is_k_diffusion_version(operation: str, version: str):
     """
-    Args:
     Compares the current k-diffusion version to a given reference with an operation.
+
+    Args:
         operation (`str`):
             A string representation of an operator, such as `">"` or `"<="`
         version (`str`):
@@ -756,8 +762,9 @@ def is_k_diffusion_version(operation: str, version: str):

 def get_objects_from_module(module):
     """
-    Args:
     Returns a dict of object names and values in a module, while skipping private/internal objects
+
+    Args:
         module (ModuleType):
             Module to extract the objects from.

@@ -775,7 +782,9 @@ def get_objects_from_module(module):

 class OptionalDependencyNotAvailable(BaseException):
-    """An error indicating that an optional dependency of Diffusers was not found in the environment."""
+    """
+    An error indicating that an optional dependency of Diffusers was not found in the environment.
+    """

 class _LazyModule(ModuleType):

Hi @a-r-r-o-w I'd like to take this up, please let me know if there are any other prerequisites I should be aware of before submitting a PR against this issue 🙂
Not prerequisites I can think of off the top of my head. Just that the PRs should be limited in scope as mentioned. You can maybe look at the Diffusers contribution guide (and philosophy, if you're interested)
I'll take up some of these.
I’m also interested in this work. Could you let me know about the current progress? @SubhasmitaSw @charchit7
Hey @yijun-lee, I've been caught up with some work, unfortunately, but I’ll work on this over the weekend or later today. If you want to get started on any of these tasks, feel free to go ahead and let us know, so we can pick up whatever is left.
Oh, actually, I think I’ll be starting this weekend as well. If we proceed separately, it would be good to inform each other through comments or other means. Have a good day :) @charchit7
Sure, @yijun-lee, that works!
you too :)
Hello there guys, I'd also like to contribute in this issue. I'm sorry I didn't really drop in a message here yet but I hope this PR helps push things forward! A g'day to all.
Feel free to take up as many files as you want (one file per PR however)! The ones mentioned in the issue description are just a few examples, but there are probably hundreds of files that could use improvements. Please keep them coming, thanks


diff --git a/src/diffusers/models/embeddings.py b/src/diffusers/models/embeddings.py
index 80775d477c0d..91451fa9aac2 100644
--- a/src/diffusers/models/embeddings.py
+++ b/src/diffusers/models/embeddings.py
@@ -86,12 +86,25 @@ def get_3d_sincos_pos_embed(
     temporal_interpolation_scale: float = 1.0,
 ) -> np.ndarray:
     r"""
+    Creates 3D sinusoidal positional embeddings.
+
     Args:
         embed_dim (`int`):
+            The embedding dimension of inputs. It must be divisible by 16.
         spatial_size (`int` or `Tuple[int, int]`):
+            The spatial dimension of positional embeddings. If an integer is provided, the same size is applied to both
+            spatial dimensions (height and width).
         temporal_size (`int`):
+            The temporal dimension of postional embeddings (number of frames).
         spatial_interpolation_scale (`float`, defaults to 1.0):
+            Scale factor for spatial grid interpolation.
         temporal_interpolation_scale (`float`, defaults to 1.0):
+            Scale factor for temporal grid interpolation.
+
+    Returns:
+        `np.ndarray`:
+            The 3D sinusoidal positional embeddings of shape `[temporal_size, spatial_size[0] * spatial_size[1],
+            embed_dim]`.
     """
     if embed_dim % 4 != 0:
         raise ValueError("`embed_dim` must be divisible by 4")
@@ -129,8 +142,24 @@ def get_2d_sincos_pos_embed(
     embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16
 ):
     """
-    grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
-    [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
+    Creates 2D sinusoidal positional embeddings.
+
+    Args:
+        embed_dim (`int`):
+            The embedding dimension.
+        grid_size (`int`):
+            The size of the grid height and width.
+        cls_token (`bool`, defaults to `False`):
+            Whether or not to add a classification token.
+        extra_tokens (`int`, defaults to `0`):
+            The number of extra tokens to add.
+        interpolation_scale (`float`, defaults to `1.0`):
+            The scale of the interpolation.
+
+    Returns:
+        pos_embed (`np.ndarray`):
+            Shape is either `[grid_size * grid_size, embed_dim]` if not using cls_token, or `[1 + grid_size*grid_size,
+            embed_dim]` if using cls_token
     """
     if isinstance(grid_size, int):
         grid_size = (grid_size, grid_size)
@@ -148,6 +177,16 @@ def get_2d_sincos_pos_embed(

 def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
+    r"""
+    This function generates 2D sinusoidal positional embeddings from a grid.
+
+    Args:
+        embed_dim (`int`): The embedding dimension.
+        grid (`np.ndarray`): Grid of positions with shape `(H * W,)`.
+
+    Returns:
+        `np.ndarray`: The 2D sinusoidal positional embeddings with shape `(H * W, embed_dim)`
+    """
     if embed_dim % 2 != 0:
         raise ValueError("embed_dim must be divisible by 2")

@@ -161,7 +200,14 @@ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):

 def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
     """
-    embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
+    This function generates 1D positional embeddings from a grid.
+
+    Args:
+        embed_dim (`int`): The embedding dimension `D`
+        pos (`numpy.ndarray`): 1D tensor of positions with shape `(M,)`
+
+    Returns:
+        `numpy.ndarray`: Sinusoidal positional embeddings of shape `(M, D)`.
     """
     if embed_dim % 2 != 0:
         raise ValueError("embed_dim must be divisible by 2")
@@ -181,7 +227,22 @@ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):

 class PatchEmbed(nn.Module):
-    """2D Image to Patch Embedding with support for SD3 cropping."""
+    """
+    2D Image to Patch Embedding with support for SD3 cropping.
+
+    Args:
+        height (`int`, defaults to `224`): The height of the image.
+        width (`int`, defaults to `224`): The width of the image.
+        patch_size (`int`, defaults to `16`): The size of the patches.
+        in_channels (`int`, defaults to `3`): The number of input channels.
+        embed_dim (`int`, defaults to `768`): The output dimension of the embedding.
+        layer_norm (`bool`, defaults to `False`): Whether or not to use layer normalization.
+        flatten (`bool`, defaults to `True`): Whether or not to flatten the output.
+        bias (`bool`, defaults to `True`): Whether or not to use bias.
+        interpolation_scale (`float`, defaults to `1`): The scale of the interpolation.
+        pos_embed_type (`str`, defaults to `"sincos"`): The type of positional embedding.
+        pos_embed_max_size (`int`, defaults to `None`): The maximum size of the positional embedding.
+    """

     def __init__(
         self,
@@ -289,7 +350,15 @@ def forward(self, latent):

 class LuminaPatchEmbed(nn.Module):
-    """2D Image to Patch Embedding with support for Lumina-T2X"""
+    """
+    2D Image to Patch Embedding with support for Lumina-T2X
+
+    Args:
+        patch_size (`int`, defaults to `2`): The size of the patches.
+        in_channels (`int`, defaults to `4`): The number of input channels.
+        embed_dim (`int`, defaults to `768`): The output dimension of the embedding.
+        bias (`bool`, defaults to `True`): Whether or not to use bias.
+    """

     def __init__(self, patch_size=2, in_channels=4, embed_dim=768, bias=True):
         super().__init__()
@@ -675,6 +744,20 @@ def get_2d_rotary_pos_embed(embed_dim, crops_coords, grid_size, use_real=True):

 def get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=False):
+    """
+    Get 2D RoPE from grid.
+
+    Args:
+    embed_dim: (`int`):
+        The embedding dimension size, corresponding to hidden_size_head.
+    grid (`np.ndarray`):
+        The grid of the positional embedding.
+    use_real (`bool`):
+        If True, return real part and imaginary part separately. Otherwise, return complex numbers.
+
+    Returns:
+        `torch.Tensor`: positional embedding with shape `( grid_size * grid_size, embed_dim/2)`.
+    """
     assert embed_dim % 4 == 0

     # use half of dimensions to encode grid_h
@@ -695,6 +778,23 @@ def get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=False):

 def get_2d_rotary_pos_embed_lumina(embed_dim, len_h, len_w, linear_factor=1.0, ntk_factor=1.0):
+    """
+    Get 2D RoPE from grid.
+
+    Args:
+    embed_dim: (`int`):
+        The embedding dimension size, corresponding to hidden_size_head.
+    grid (`np.ndarray`):
+        The grid of the positional embedding.
+    linear_factor (`float`):
+        The linear factor of the positional embedding, which is used to scale the positional embedding in the linear
+        layer.
+    ntk_factor (`float`):
+        The ntk factor of the positional embedding, which is used to scale the positional embedding in the ntk layer.
+
+    Returns:
+        `torch.Tensor`: positional embedding with shape `( grid_size * grid_size, embed_dim/2)`.
+    """
     assert embed_dim % 4 == 0

     emb_h = get_1d_rotary_pos_embed(

Hi @a-r-r-o-w I'd like to take this up, please let me know if there are any other prerequisites I should be aware of before submitting a PR against this issue 🙂
Not prerequisites I can think of off the top of my head. Just that the PRs should be limited in scope as mentioned. You can maybe look at the Diffusers contribution guide (and philosophy, if you're interested)
I'll take up some of these.
I’m also interested in this work. Could you let me know about the current progress? @SubhasmitaSw @charchit7
Hey @yijun-lee, I've been caught up with some work, unfortunately, but I’ll work on this over the weekend or later today. If you want to get started on any of these tasks, feel free to go ahead and let us know, so we can pick up whatever is left.
Oh, actually, I think I’ll be starting this weekend as well. If we proceed separately, it would be good to inform each other through comments or other means. Have a good day :) @charchit7
Sure, @yijun-lee, that works!
you too :)


diff --git a/sktime/datatypes/_adapter/polars.py b/sktime/datatypes/_adapter/polars.py
index e1fdd5f3ab7..e8138e4faa9 100644
--- a/sktime/datatypes/_adapter/polars.py
+++ b/sktime/datatypes/_adapter/polars.py
@@ -226,22 +226,31 @@ def check_polars_frame(

     # columns in polars are unique, no check required

+    if lazy:
+        width = obj.collect_schema().len()
+        columns = obj.collect_schema().names()
+        dtypes = obj.collect_schema().dtypes()
+    else:
+        width = obj.width
+        columns = obj.columns
+        dtypes = obj.dtypes
+
     if _req("is_empty", return_metadata):
-        metadata["is_empty"] = obj.width < 1
+        metadata["is_empty"] = width < 1
     if _req("is_univariate", return_metadata):
-        metadata["is_univariate"] = obj.width - len(index_cols) == 1
+        metadata["is_univariate"] = width - len(index_cols) == 1
     if _req("n_features", return_metadata):
-        metadata["n_features"] = obj.width - len(index_cols)
+        metadata["n_features"] = width - len(index_cols)
     if _req("feature_names", return_metadata):
-        feature_columns = [x for x in obj.columns if x not in index_cols]
+        feature_columns = [x for x in columns if x not in index_cols]
         metadata["feature_names"] = feature_columns
     if _req("dtypekind_dfip", return_metadata):
         index_cols_count = len(index_cols)
-        dtype_list = obj.dtypes[index_cols_count:]
+        dtype_list = dtypes[index_cols_count:]
         metadata["dtypekind_dfip"] = _polars_dtype_to_kind(dtype_list)
     if _req("feature_kind", return_metadata):
         index_cols_count = len(index_cols)
-        dtype_list = obj.dtypes[index_cols_count:]
+        dtype_list = dtypes[index_cols_count:]
         dtype_kind = _polars_dtype_to_kind(dtype_list)
         metadata["feature_kind"] = _get_feature_kind(dtype_kind)

[ENH] `polars` schema checks - address performance warnings
The current schema checks for lazy `polars` based data types raise performance warnings, e.g.,

```
sktime/datatypes/tests/test_check.py::test_check_metadata_inference[Table-polars_lazy_table-fixture:1]
  /home/runner/work/sktime/sktime/sktime/datatypes/_adapter/polars.py:234: PerformanceWarning: Determining the width of a LazyFrame requires resolving its schema, which is a potentially expensive operation. Use `LazyFrame.collect_schema().len()` to get the width without this warning.
    metadata["n_features"] = obj.width - len(index_cols)
```

These should be addressed.

The tests to execute to check whether these warnings persist are those in the `datatypes` module - these are automatically executed for a change in the impacted file, on remote CI.