o
    i	                     @   sh   d dl mZ d dlmZmZ d dlZddlmZ ddlm	Z	 ddl
mZ dd	lmZ G d
d deZdS )    )BytesIO)AnyOptionalN   )torch)get_torch_default_device   )PyTorchShim)PyTorchGradScalerc                       s^   e Zd ZdZ					dded dededee d	ed
 f
 fddZdd Z	dd Z
  ZS )TorchScriptShima  A Thinc shim that wraps a TorchScript module.

    model:
        The TorchScript module. A value of `None` is also possible to
        construct a shim to deserialize into.
    mixed_precision:
        Enable mixed-precision. This changes whitelisted ops to run
        in half precision for better performance and lower memory use.
    grad_scaler:
        The gradient scaler to use for mixed-precision training. If this
        argument is set to "None" and mixed precision is enabled, a gradient
        scaler with the default configuration is used.
    device:
        The PyTorch device to run the model on. When this argument is
        set to "None", the default device for the currently active Thinc
        ops is used.
    NFmodelztorch.jit.ScriptModule	optimizermixed_precisiongrad_scalerdeviceztorch.devicec                    s8   |d urt |tjjstdt |||||| d S )NzUPyTorchScriptShim must be initialized with ScriptModule or None (for deserialization))
isinstancer   jitScriptModule
ValueErrorsuper__init__)selfr   configr   r   r   r   	__class__ K/home/ubuntu/.local/lib/python3.10/site-packages/thinc/shims/torchscript.pyr      s
   	zTorchScriptShim.__init__c                 C   s>   t  }tj| j| |d | }| j|d}t	|S )Nr   )r   r   )
r   r   r   save_modelseekgetvaluecfgsrslymsgpack_dumps)r   filelikemodel_bytesmsgr   r   r   to_bytes/   s   

zTorchScriptShim.to_bytesc                 C   sv   t  }t|}|d | _t|d }|d |jdkr"tdn|}tj	j
||d| _| j| | j| | S )Nr   r   r   mpscpu)map_location)r   r"   msgpack_loadsr!   r   r   typer   r   r   loadr   to_grad_scalerto_)r   
bytes_datar   r&   r$   r*   r   r   r   
from_bytes7   s   


zTorchScriptShim.from_bytes)NNFNN)__name__
__module____qualname____doc__r   r   boolr
   r   r'   r2   __classcell__r   r   r   r   r      s(    r   )ior   typingr   r   r"   compatr   utilr   pytorchr	   pytorch_grad_scalerr
   r   r   r   r   r   <module>   s    