
    sh"b                        S SK r S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	J
r
  S SKJrJr  S SKJrJrJrJrJr  S SKrS SKJs  Jr  S SKJr  S SKJr  S SKJr  S SKJr  S S	KJ r J!r!J"r"J#r#  \(       a  S S
K$J%r%  S SK&J'r'  / SQr(S SK)rSSK*J+r+  SSK,J-r-J.r.J/r/J0r0  SSK1J2r2J3r3J4r4J5r5  SSK6J7r7J8r8  SSK9J:r:J9r9J;r;  \\Rx                  Rz                  /\\   4   r> S3SSSS.S\R~                  R                  S\A\S4   S\\B\C\4      S\\\B\C\4   \A\   \D\   4      S\ES\A\CS4   S\34S jjjrF S3SSSSS.S\R~                  R                  S\A\S4   S\\B\C\4      S\\\B\C\4   \A\   \D\   4      S\ES\A\CS4   S \\BS!\\   4      S\34S" jjjrG S3SSSS.S\R~                  R                  S\A\S4   S\\B\C\4      S\\\B\C\4   \A\   \D\   4      S\ES\A\CS4   S\34S# jjjrHS$rISS\IS%.S&\3S'\S(\\B\C\4      S)\\B\C\J4      S*\JSS4S+ jjrKSSS,.S'\S(\\B\C\4      S-\\B\C\J4      S\34S. jjrLSS/.S0\M\   S1\\C   SS4S2 jjrNg)4    N)Iterator)autoEnum)AnyCallableOptionalTYPE_CHECKINGUnion)compatibility)
PassResult)PassManager)FileLike)FlattenFuncFromDumpableContextFnToDumpableContextFnUnflattenFunc)
OpOverload)StrictMinMaxConstraint)
ConstraintDimExportBackwardSignatureExportGraphSignatureExportedProgramCustomDecompTableModuleCallEntryModuleCallSignaturedefault_decompositionsdimsexportexport_for_trainingexport_for_inferenceloadregister_dataclasssave	unflattenFlatArgsAdapterUnflattenedModule   )r   )r   r   r   ShapesCollection)r   r   r   r   )r   r   )r&   r%   r'   T dynamic_shapesstrictpreserve_module_call_signaturemodargs.kwargsr,   r-   r.   returnc          	         SSK Jn  [        U [        R                  R
                  5      (       d  [        S[        U 5       S35      e[        U [        R                  R                  5      (       a  [        S5      eU" U UUUUUS9$ )a  
:func:`export_for_training` takes any nn.Module along with example inputs, and produces a traced graph representing
only the Tensor computation of the function in an Ahead-of-Time (AOT) fashion,
which can subsequently be executed with different inputs or serialized. The
traced graph (1) produces normalized operators in the all ATen operator set
(as well as any user-specified custom operators), (2) has eliminated all Python control
flow and data structures (with certain exceptions), and (3) records the set of
shape constraints needed to show that this normalization and control-flow elimination
is sound for future inputs. This API is intended for PT2 quantization training use cases
and will soon be the default IR of torch.export.export in the near future. To read further about
the motivation behind this change, please refer to
https://dev-discuss.pytorch.org/t/why-pytorch-does-not-need-a-new-standardized-operator-set/2206
With this API, and :func:`run_decompositions()`, you should be able to get inference IR with
your custom decomposition behaviour.

**Soundness Guarantee**

See :func:`export()` docstring for more details.

Args:
    mod: We will trace the forward method of this module.

    args: Example positional inputs.

    kwargs: Optional example keyword inputs.

    dynamic_shapes:
     An optional argument where the type should either be:
     1) a dict from argument names of ``f`` to their dynamic shape specifications,
     2) a tuple that specifies dynamic shape specifications for each input in original order.
     If you are specifying dynamism on keyword args, you will need to pass them in the order that
     is defined in the original function signature.

     The dynamic shape of a tensor argument can be specified as either
     (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is
     not required to include static dimension indices in this dict, but when they are,
     they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None,
     where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions
     are denoted by None. Arguments that are dicts or tuples / lists of tensors are
     recursively specified by using mappings or sequences of contained specifications.

    strict: When enabled (default), the export function will trace the program through
     TorchDynamo which will ensure the soundness of the resulting graph. Otherwise, the
     exported program will not validate the implicit assumptions baked into the graph and
     may cause behavior divergence between the original model and the exported one. This is
     useful when users need to workaround bugs in the tracer, or simply want incrementally
     enable safety in their models. Note that this does not affect the resulting IR spec
     to be different and the model will be serialized in the same way regardless of what value
     is passed here.
     WARNING: This option is experimental and use this at your own risk.

Returns:
    An :class:`ExportedProgram` containing the traced callable.

**Acceptable input/output types**

Acceptable types of inputs (for ``args`` and ``kwargs``) and outputs include:

- Primitive types, i.e. ``torch.Tensor``, ``int``, ``float``, ``bool`` and ``str``.
- Dataclasses, but they must be registered by calling :func:`register_dataclass` first.
- (Nested) Data structures comprising of ``dict``, ``list``, ``tuple``, ``namedtuple`` and
  ``OrderedDict`` containing all above types.

r(   )_export_for_training;Expected `mod` to be an instance of `torch.nn.Module`, got .Exporting a ScriptModule is not supported. Maybe try converting your ScriptModule to an ExportedProgram using `TS2EPConverter(mod, args, kwargs).convert()` instead.)r-   r.   )
_tracer4   
isinstancetorchnnModule
ValueErrortypejitScriptModule)r/   r0   r1   r,   r-   r.   r4   s          i/Users/tiagomarins/Projetos/claudeai/copy_bank/venv/lib/python3.13/site-packages/torch/export/__init__.pyr    r    K   s    R -c588??++I$s)TUV
 	
 #uyy--..K
 	

  'E     )r,   r-   r.   decomp_tablerC   r   c          	      <    [        U UUUUUS9nUR                  US9$ )a  
:func:`export_for_inference` takes any nn.Module along with example inputs, and produces a traced graph representing
only the Tensor computation of the function in an Ahead-of-Time (AOT) fashion,
which can subsequently be executed with different inputs or serialized. The
traced graph (1) produces normalized operators in the ATen operator set
(as well as any user-specified custom operators) which is customizable via decomp_table,
(2) has eliminated all Python control flow and data structures (with certain exceptions),
and (3) records the set of shape constraints needed to show that this normalization and control-flow
elimination is sound for future inputs. This API is for convenience use as it combines :func:`export_for_training` and
:func:`run_decompositions`.

**Soundness Guarantee**

See :func:`export()` docstring for more details.

Args:
    mod: We will trace the forward method of this module.

    args: Example positional inputs.

    kwargs: Optional example keyword inputs.

    dynamic_shapes:
     An optional argument where the type should either be:
     1) a dict from argument names of ``f`` to their dynamic shape specifications,
     2) a tuple that specifies dynamic shape specifications for each input in original order.
     If you are specifying dynamism on keyword args, you will need to pass them in the order that
     is defined in the original function signature.

     The dynamic shape of a tensor argument can be specified as either
     (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is
     not required to include static dimension indices in this dict, but when they are,
     they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None,
     where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions
     are denoted by None. Arguments that are dicts or tuples / lists of tensors are
     recursively specified by using mappings or sequences of contained specifications.

    strict: When enabled (default), the export function will trace the program through
     TorchDynamo which will ensure the soundness of the resulting graph. Otherwise, the
     exported program will not validate the implicit assumptions baked into the graph and
     may cause behavior divergence between the original model and the exported one. This is
     useful when users need to workaround bugs in the tracer, or simply want incrementally
     enable safety in their models. Note that this does not affect the resulting IR spec
     to be different and the model will be serialized in the same way regardless of what value
     is passed here.
     WARNING: This option is experimental and use this at your own risk.

    decomp_table: See :func:`run_decompositions` for more details.

Returns:
    An :class:`ExportedProgram` containing the traced callable.

**Acceptable input/output types**

Acceptable types of inputs (for ``args`` and ``kwargs``) and outputs include:

- Primitive types, i.e. ``torch.Tensor``, ``int``, ``float``, ``bool`` and ``str``.
- Dataclasses, but they must be registered by calling :func:`register_dataclass` first.
- (Nested) Data structures comprising of ``dict``, ``list``, ``tuple``, ``namedtuple`` and
  ``OrderedDict`` containing all above types.

r+   )rC   )r    run_decompositions)r/   r0   r1   r,   r-   r.   rC   ep_for_trainings           rA   r!   r!      s7    R *%'EO --<-HHrB   c          
         SSK Jn  [        U [        R                  R
                  5      (       d  [        S[        U 5       S35      e[        U [        R                  R                  5      (       a  [        S5      eU" U UUUUUSS9$ )a  
:func:`export` takes any nn.Module along with example inputs, and produces a traced graph representing
only the Tensor computation of the function in an Ahead-of-Time (AOT) fashion,
which can subsequently be executed with different inputs or serialized.  The
traced graph (1) produces normalized operators in the functional ATen operator set
(as well as any user-specified custom operators), (2) has eliminated all Python control
flow and data structures (with certain exceptions), and (3) records the set of
shape constraints needed to show that this normalization and control-flow elimination
is sound for future inputs.

**Soundness Guarantee**

While tracing, :func:`export()` takes note of shape-related assumptions
made by the user program and the underlying PyTorch operator kernels.
The output :class:`ExportedProgram` is considered valid only when these
assumptions hold true.

Tracing makes assumptions on the shapes (not values) of input tensors.
Such assumptions must be validated at graph capture time for :func:`export`
to succeed. Specifically:

- Assumptions on static shapes of input tensors are automatically validated without additional effort.
- Assumptions on dynamic shape of input tensors require explicit specification
  by using the :func:`Dim` API to construct dynamic dimensions and by associating
  them with example inputs through the ``dynamic_shapes`` argument.

If any assumption can not be validated, a fatal error will be raised. When that happens,
the error message will include suggested fixes to the specification that are needed
to validate the assumptions. For example :func:`export` might suggest the
following fix to the definition of a dynamic dimension ``dim0_x``, say appearing in the
shape associated with input ``x``, that was previously defined as ``Dim("dim0_x")``::

    dim = Dim("dim0_x", max=5)

This example means the generated code requires dimension 0 of input ``x`` to be less
than or equal to 5 to be valid. You can inspect the suggested fixes to dynamic dimension
definitions and then copy them verbatim into your code without needing to change the
``dynamic_shapes`` argument to your :func:`export` call.

Args:
    mod: We will trace the forward method of this module.

    args: Example positional inputs.

    kwargs: Optional example keyword inputs.

    dynamic_shapes:
     An optional argument where the type should either be:
     1) a dict from argument names of ``f`` to their dynamic shape specifications,
     2) a tuple that specifies dynamic shape specifications for each input in original order.
     If you are specifying dynamism on keyword args, you will need to pass them in the order that
     is defined in the original function signature.

     The dynamic shape of a tensor argument can be specified as either
     (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is
     not required to include static dimension indices in this dict, but when they are,
     they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None,
     where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions
     are denoted by None. Arguments that are dicts or tuples / lists of tensors are
     recursively specified by using mappings or sequences of contained specifications.

    strict: When enabled (default), the export function will trace the program through
     TorchDynamo which will ensure the soundness of the resulting graph. Otherwise, the
     exported program will not validate the implicit assumptions baked into the graph and
     may cause behavior divergence between the original model and the exported one. This is
     useful when users need to workaround bugs in the tracer, or simply want incrementally
     enable safety in their models. Note that this does not affect the resulting IR spec
     to be different and the model will be serialized in the same way regardless of what value
     is passed here.
     WARNING: This option is experimental and use this at your own risk.

Returns:
    An :class:`ExportedProgram` containing the traced callable.

**Acceptable input/output types**

Acceptable types of inputs (for ``args`` and ``kwargs``) and outputs include:

- Primitive types, i.e. ``torch.Tensor``, ``int``, ``float``, ``bool`` and ``str``.
- Dataclasses, but they must be registered by calling :func:`register_dataclass` first.
- (Nested) Data structures comprising of ``dict``, ``list``, ``tuple``, ``namedtuple`` and
  ``OrderedDict`` containing all above types.

r(   )_exportr5   r6   r7   T)r-   r.   pre_dispatch)
r8   rH   r9   r:   r;   r<   r=   r>   r?   r@   )r/   r0   r1   r,   r-   r.   rH   s          rA   r   r      s    z  c588??++I$s)TUV
 	
 #uyy--..K
 	

 'E rB      )extra_filesopset_versionpickle_protocolepfrK   rL   rM   c          
         [        U [        5      (       d"  [        S[        U 5      R                   S35      eSSKJn  SSKJnJ	n  U" XU5      n[        U[        [        R                  45      (       a  [        R                  " U5      n[        R                  " US5       n	[        UR                   ["        5      (       d   eU	R%                  SUR                   5        U	R%                  SUR&                  5        U	R%                  S	UR(                  5        U	R%                  S
UR*                  5        U	R%                  SSR-                  [/        [        U5      5      5        U(       a?  UR1                  5        H+  u  pUR3                  S5      nU	R%                  SU
 3U5        M-     SSS5        g! , (       d  f       g= f)a  

.. warning::
    Under active development, saved files may not be usable in newer versions
    of PyTorch.

Saves an :class:`ExportedProgram` to a file-like object. It can then be
loaded using the Python API :func:`torch.export.load <torch.export.load>`.

Args:
    ep (ExportedProgram): The exported program to save.

    f (str | os.PathLike[str] | IO[bytes]) A file-like object (has to
     implement write and flush) or a string containing a file name.

    extra_files (Optional[Dict[str, Any]]): Map from filename to contents
     which will be stored as part of f.

    opset_version (Optional[Dict[str, int]]): A map of opset names
     to the version of this opset

    pickle_protocol: can be specified to override the default protocol

Example::

    import torch
    import io

    class MyModule(torch.nn.Module):
        def forward(self, x):
            return x + 10

    ep = torch.export.export(MyModule(), (torch.randn(5),))

    # Save to file
    torch.export.save(ep, 'exported_program.pt2')

    # Save to io.BytesIO buffer
    buffer = io.BytesIO()
    torch.export.save(ep, buffer)

    # Save with extra files
    extra_files = {'foo.txt': b'bar'.decode('utf-8')}
    torch.export.save(ep, 'exported_program.pt2', extra_files=extra_files)

zBThe 'ep' parameter must be an instance of 'ExportedProgram', got 'z
' instead.r   SCHEMA_VERSION)	serializeSerializedArtifactw serialized_exported_program.jsonserialized_state_dict.ptserialized_constants.ptserialized_example_inputs.ptversionr6   utf-8zextra_files/N)r9   r   	TypeErrorr>   __name__torch._export.serde.schemarR   torch._export.serde.serializerS   rT   strosPathLikefspathzipfileZipFileexported_programbyteswritestr
state_dict	constantsexample_inputsjoinmapitemsencode)rN   rO   rK   rL   rM   rR   rS   rT   artifactzipfextra_file_namecontentencoded_contents                rA   r$   r$   v  sX   l b/**PQUVXQYQbQbPccmn
 	
 :K#,R#PH!c2;;'((IIaL	C	 D(33U;;;;8(:S:ST0(2E2EF/1C1CD4h6M6MNi#c>*B!CD ,7,=,=,?(").."9_,=>P -@ 
!	 	 s   !DF11
F?)rK   expected_opset_versionru   c                   [        U [        [        R                  45      (       a  [        R                  " U 5      n U=(       d    0 n[
        R                  " U S5       nUR                  S5      R                  5       R                  S5      nSSK
Jn  [        U5      [        U5      :X  d   eUS   [        US   5      :w  a  [        SU SU S35      eSSKJnJn  S	nS	n	S	n
S	nUR#                  5        GH  nUR                  UR$                  5      nUR$                  S
:X  a  UnM3  UR$                  S:X  a  [&        R(                  " S5        Un	M]  UR$                  S:X  a  [&        R(                  " S5        Un
M  UR$                  S:X  a  Un	M  UR$                  S:X  a  Un
M  UR$                  S:X  a  UnM  UR$                  R+                  S5      (       d  M  UR$                  R                  SS5      S   nUR                  S5      X'   GM     Uc   eU	c   eU
c   eUc   eU" UU	U
U5      nU" X5      nUsS	S	S	5        $ ! , (       d  f       g	= f)a  

.. warning::
    Under active development, saved files may not be usable in newer versions
    of PyTorch.

Loads an :class:`ExportedProgram` previously saved with
:func:`torch.export.save <torch.export.save>`.

Args:
    f (str | os.PathLike[str] | IO[bytes]): A file-like object (has to
     implement write and flush) or a string containing a file name.

    extra_files (Optional[Dict[str, Any]]): The extra filenames given in
     this map would be loaded and their content would be stored in the
     provided map.

    expected_opset_version (Optional[Dict[str, int]]): A map of opset names
     to expected opset versions

Returns:
    An :class:`ExportedProgram` object

Example::

    import torch
    import io

    # Load ExportedProgram from file
    ep = torch.export.load('exported_program.pt2')

    # Load ExportedProgram from io.BytesIO object
    with open('exported_program.pt2', 'rb') as f:
        buffer = io.BytesIO(f.read())
    buffer.seek(0)
    ep = torch.export.load(buffer)

    # Load with extra files.
    extra_files = {'foo.txt': ''}  # values will be replaced with data
    ep = torch.export.load('exported_program.pt2', extra_files=extra_files)
    print(extra_files['foo.txt'])
    print(ep(torch.randn(5)))
rrZ   r6   r   rQ   zSerialized version z+ does not match our current schema version )deserializerT   NrV   zserialized_state_dict.jsonz"This version of file is deprecatedzserialized_constants.jsonrW   rX   rY   rK   /r(   r[   )r9   r`   ra   rb   rc   rd   re   readdecodesplitr^   rR   lenRuntimeErrorr_   rx   rT   infolistfilenamewarningswarn
startswith)rO   rK   ru   rq   rZ   rR   rx   rT   serialized_exported_programserialized_state_dictserialized_constantsserialized_example_inputs	file_infofile_contentr   rp   rN   s                    rA   r"   r"     sA   b !c2;;'((IIaL#K	C	 D))I&--/55c:=7|s>22221:^A.//%gY /""0!14 
 	R 8<#150459!I99Y%7%78L!!%GG.:+##'CCBC(4%##'BBBC'3$##'AA(4%##'@@'3$##'EE,8)##..}==$--33C;A>(4(;(;G(D%' )* +666$000#///(444'9'! %	(
 :q 
!	 	 s   E7IAI
Iserialized_type_nameclsr   c                    SSK Jn  U" XS9$ )a  
Registers a dataclass as a valid input/output type for :func:`torch.export.export`.

Args:
    cls: the dataclass type to register
    serialized_type_name: The serialized name for the dataclass. This is
    required if you want to serialize the pytree TreeSpec containing this
    dataclass.

Example::

    import torch
    from dataclasses import dataclass

    @dataclass
    class InputDataClass:
        feature: torch.Tensor
        bias: int

    @dataclass
    class OutputDataClass:
        res: torch.Tensor

    torch.export.register_dataclass(InputDataClass)
    torch.export.register_dataclass(OutputDataClass)

    class Mod(torch.nn.Module):
        def forward(self, x: InputDataClass) -> OutputDataClass:
            res = x.feature + x.bias
            return OutputDataClass(res=res)

    ep = torch.export.export(Mod(), (InputDataClass(torch.ones(2, 2), 1), ))
    print(ep)

r   )!register_dataclass_as_pytree_noder   )torch._export.utilsr   )r   r   r   s      rA   r#   r#   ;  s    R F, rB   )N)Obuiltinscopydataclassesinspectra   systypingr   rd   collections.abcr   enumr   r   r   r   r   r	   r
   r:   torch.utils._pytreeutils_pytreepytreetorch.fx._compatibilityr   torch.fx.passes.infra.pass_baser   "torch.fx.passes.infra.pass_managerr   torch.typesr   r   r   r   r   
torch._opsr   %torch.fx.experimental.symbolic_shapesr   __all__torch.export.custom_opsdecomp_utilsr   r,   r   r   r   r)   rf   r   r   r   r   graph_signaturer   r   r%   r&   r'   fxGraphModulePassTyper;   r<   tupledictr`   listboolr    r!   r   DEFAULT_PICKLE_PROTOCOLintr$   r"   r>   r#   r*   rB   rA   <module>r      s       	 
    $  @ @  $ $ 1 6 :     &L.  + C C  K D D UXX))*HZ,@@A (,\
 NR68\	\
S/\ T#s(^$\
 U4S>5:tCy#HIJ\ \ %*#s(O\ \D (,RI
 NR68EIRI	RI
S/RI T#s(^$RI
 U4S>5:tCy#HIJRI RI %*#s(ORI 4hx.@ @ABRI RIp (,q
 NR68q	q
S/q T#s(^$q
 U4S>5:tCy#HIJq q %*#s(Oq qh   -1.22QQQQQQ $sCx.)	QQ
 DcN+QQ QQ 
QQn -17;	nn $sCx.)n %T#s(^4	n
 nh +/-	c- #3-- 
	-rB   