category stringclasses 107
values | title stringlengths 15 179 | question_link stringlengths 59 147 | question_body stringlengths 53 33.8k | answer_html stringlengths 0 28.8k | __index_level_0__ int64 0 1.58k |
|---|---|---|---|---|---|
transformers | Huggingface AutoTokenizer cannot be referenced when importing Transformers | https://stackoverflow.com/questions/68481189/huggingface-autotokenizer-cannot-be-referenced-when-importing-transformers | <p>I am trying to import AutoTokenizer and AutoModelWithLMHead, but I am getting the following error:</p>
<p>ImportError: cannot import name 'AutoTokenizer' from partially initialized module 'transformers' (most likely due to a circular import)</p>
<p>First, I install transformers: <code>pip install transformers</code>... | <p>For anyone who comes across a problem around circular import, this could be due to the naming convention of your <code>.py</code> file. Changing my file name solved the issue as there might be a file in my Python lib folder with similar naming conventions.</p>
| 434 |
transformers | cannot import name 'TrainingArguments' from 'transformers' | https://stackoverflow.com/questions/70066746/cannot-import-name-trainingarguments-from-transformers | <p>I am trying to fine-tune a pretrained huggingface BERT model. I am importing the following</p>
<pre><code>from transformers import (AutoTokenizer, AutoConfig,
AutoModelForSequenceClassification, TrainingArguments, Trainer)
</code></pre>
<p>and get the following error:</p>
<pre><code>can... | <p>Find out the version of the transformers lib installed.</p>
<pre><code>import transformers
print(transformers.__version__)
</code></pre>
<p>Somehow <code>pip install</code> doesn't install the latest version. I think we need to have v4.20.0 or greater.</p>
<p>you can try the following to install the latest version.... | 435 |
transformers | Are applicative transformers really superfluous? | https://stackoverflow.com/questions/37761078/are-applicative-transformers-really-superfluous | <p>There is a lot of talk about <code>Applicative</code> <em>not</em> needing its own transformer class, like this:</p>
<pre><code>class AppTrans t where
liftA :: Applicative f => f a -> t f a
</code></pre>
<p>But I can define applicative transformers that don't seem to be compositions of applicatives! For ... | <p>Great question! I believe there are two different parts of this question:</p>
<ol>
<li><strong>Composing</strong> existing applicatives or monads into more complex ones.</li>
<li><strong>Constructing all</strong> applicatives/monads from some given starting set.</li>
</ol>
<p>Ad 1.: <strong>Monad transformers are ... | 436 |
transformers | Spacy-Transformers: Access GPT-2? | https://stackoverflow.com/questions/68946827/spacy-transformers-access-gpt-2 | <p>I'm using Spacy-Transformers to build some NLP models.</p>
<p>The <a href="https://spacy.io/universe/project/spacy-transformers#gatsby-noscript" rel="nofollow noreferrer">Spacy-Transformers docs</a> say:</p>
<blockquote>
<p><strong>spacy-transformers</strong></p>
<p><em>spaCy pipelines for pretrained BERT, XLNet and... | <p>The <code>en_core_web_trf</code> uses a specific Transformers model, but you can specify arbitrary ones using the <code>TransformerModel</code> wrapper class from <code>spacy-transformers</code>. See <a href="https://spacy.io/api/architectures#TransformerModel" rel="nofollow noreferrer">the docs</a> for that. An exa... | 437 |
transformers | issue when importing BloomTokenizer from transformers in python | https://stackoverflow.com/questions/73107703/issue-when-importing-bloomtokenizer-from-transformers-in-python | <p>I am trying to import BloomTokenizer from transformers</p>
<pre><code>from transformers import BloomTokenizer
</code></pre>
<p>and I receive the following error</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'BloomTokenize... | <p>BLOOM has no slow tokenizer class. It only has a <a href="https://huggingface.co/docs/transformers/model_doc/bloom#transformers.BloomTokenizerFast" rel="nofollow noreferrer">fast tokenizer</a>. The official documentation is wrong at this point. Use the following instead:</p>
<pre class="lang-py prettyprint-override"... | 438 |
transformers | huggingface/transformers: cache directory | https://stackoverflow.com/questions/73594934/huggingface-transformers-cache-directory | <p>I'm trying to use huggingface transformers.
(Win 11, Python 3.9, jupyternotebook, virtual environment)</p>
<p>When I ran code:</p>
<pre><code>from transformers import pipeline
print(pipeline('sentiment-analysis')('I hate you'))
</code></pre>
<p>I got an error :</p>
<blockquote>
<p>FileNotFoundError: [WinError 3] The... | 439 | |
transformers | TypeScript custom transformers with ts.createWatchProgram | https://stackoverflow.com/questions/62026189/typescript-custom-transformers-with-ts-createwatchprogram | <p>TypeScript has several high-level APIs to implement <strong>watch/compile,</strong> for example:</p>
<ul>
<li><a href="https://github.com/microsoft/TypeScript/blob/0b38a9a2b03d3c651822bc2a20d381545384f0f5/src/compiler/watchPublic.ts#L196" rel="nofollow noreferrer"><b>createWatchCompilerHost</b>( rootFiles, options... | <p>Better approach, more aligned with <a href="https://github.com/microsoft/TypeScript/pull/31432" rel="nofollow noreferrer">solutionBuilder.<strong>getNextInvalidatedProject()</strong></a> recommendation.</p>
<p>When you call <strong>solutionBuilder.getNextInvalidatedProject() .emit(...)</strong> manually, you can pa... | 440 |
transformers | Including multiple dataset transformers in custom transformer | https://stackoverflow.com/questions/77570948/including-multiple-dataset-transformers-in-custom-transformer | <p>Here is my custom transformer, meant to transform the subject dataframe of encoding and scaling:</p>
<pre><code>class DfGrooming(BaseEstimator, TransformerMixin):
def __init__(self):
self.encodable_columns = ['Education','EmploymentType','MaritalStatus', 'HasMortgage', 'HasDependents', 'LoanPurpose', 'Ha... | 441 | |
transformers | What are Haskell's monad transformers in categorical terms? | https://stackoverflow.com/questions/6854303/what-are-haskells-monad-transformers-in-categorical-terms | <p>As a math student, the first thing I did when I learned about monads in Haskell was check that they really were monads in the sense I knew about. But then I learned about monad transformers and those don't quite seem to be something studied in category theory.</p>
<p>In particular I would expect them to be related ... | <p>Monad transformers aren't exceedingly mathematically pleasant. However, we can get nice (co)products from free monads, and, more generally, ideal monads: See Ghani and Uustalu's "Coproducts of Ideal Monads": <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.2698">http://citeseerx.ist.psu.edu/viewdoc... | 442 |
transformers | Monad Transformers lift | https://stackoverflow.com/questions/39638546/monad-transformers-lift | <p>I was just looking into monad transformers in real world Haskell.
The book said that to make something a monad transformer, you need to make it an instance of the MonadTrans type class.</p>
<p>So the book defined a new Transformer, the <code>MaybeT m a</code> transformer.</p>
<p>They defined the monadTrans type cl... | <blockquote>
<p>but you can use functions like get,put,tell etc without actually doing any lifting</p>
</blockquote>
<p>This is because those functions are actually defined on e.g. the <code>MonadState</code> typeclass, not <code>State</code> type. </p>
<pre><code>class Monad m => MonadState s m | m -> s wher... | 443 |
transformers | Rxjava how to generify transformers? | https://stackoverflow.com/questions/54901081/rxjava-how-to-generify-transformers | <p>I've found myself writing a lot of transformers to generify some stream operations such as retry, apply schedulers, etc. Which made me write a lot of code duplication because each stream type(single, completable, etc.) has it's own Transformer so I had to implement 4 different transformers which do exactly the same.... | 444 | |
transformers | RuntimeError: Numpy is not available (transformers) | https://stackoverflow.com/questions/78863932/runtimeerror-numpy-is-not-available-transformers | <p>I basically just want to use the transformers pipeline() to classify data, but independent of which model I try to use, it returns the same error, stating <strong>Numpy is not available</strong></p>
<p>Code I'm running:</p>
<pre><code>pipe = pipeline("text-classification", model="AdamLucek/roberta-lla... | <p>Try:</p>
<pre><code>pip install "numpy<2"
</code></pre>
<p>then restart the kernel.</p>
| 445 |
transformers | issue when import ConditionalGeneration from transformers in python | https://stackoverflow.com/questions/74101343/issue-when-import-conditionalgeneration-from-transformers-in-python | <p>I am trying to import ConditionalGeneration from transformers in jupyter notebook</p>
<pre><code>from transformers import ConditionalGeneration
</code></pre>
<p>but encounter following error.I install different version and different method for installing pytorch and transformers but I can't solve it.</p>
<pre><code>... | <p>There is no class named ConditionalGeneration in transformers simply)
you need to specify one of the classes for example <a href="https://huggingface.co/docs/transformers/v4.23.1/en/model_doc/bart#transformers.BartForConditionalGeneration" rel="nofollow noreferrer">BartForConditionalGeneration</a>, <a href="https... | 446 |
transformers | Missing convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py (notebook/Jupyter/transformers) | https://stackoverflow.com/questions/77519523/missing-convert-trajectory-transformer-original-pytorch-checkpoint-to-pytorch-py | <p>I tried on a notebook to install the package transformers, it failed:</p>
<p><code>!pip install transformers</code></p>
<p>I get this:</p>
<pre><code>FULLTRACE:
Collecting transformers
Obtaining dependency information for transformers from https://files.pythonhosted.org/packages/12/dd/f17b11a93a9ca27728e12512d167e... | <p>I was trying to load transformers onto my local system and had the same error. (Windows 11 Home)</p>
<p>I opened Registry Editor, navigated to:</p>
<p>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem</p>
<p>found the value:</p>
<p>LongPathsEnabled</p>
<p>then changed the value from 0 to 1. (hexadecimal... | 447 |
transformers | How to import Transformers with Tensorflow | https://stackoverflow.com/questions/74914230/how-to-import-transformers-with-tensorflow | <p>After installing Transformers using</p>
<pre><code>pip install Transformers
</code></pre>
<p>I get version 4.25.1 , but when I try to import Transformer by</p>
<pre><code>from tensorflow.keras.layers import Transformer
# or
from tensorflow.keras.layers.experimental import Transformer
</code></pre>
<p>I get this err... | <p>Since you have installed Transformers directly you would have to directly import transformers, as in</p>
<pre><code>import transformers
</code></pre>
| 448 |
transformers | Laravel Dingo nested transformers | https://stackoverflow.com/questions/44900145/laravel-dingo-nested-transformers | <p>I'm trying to get one to many relationship objects with transformers. I want to get include metas but i only get just regular transform fields.</p>
<p>my transformer:</p>
<pre><code>class AssistantTransformer extends TransformerAbstract
{
protected $availableIncludes = [
'assistantmetas'
];
p... | <p>Just use <code>defaultIncludes</code> not available includes, because it needs to send request via <code>url? include=assistantmetas</code> to get result like this.</p>
| 449 |
transformers | How to change huggingface transformers default cache directory? | https://stackoverflow.com/questions/63312859/how-to-change-huggingface-transformers-default-cache-directory | <p>The default cache directory lacks disk capacity, I need to change the configuration of the default cache directory. How can I do that?</p>
| <p>You can specify the cache directory whenever you load a model with <a href="https://huggingface.co/transformers/main_classes/model.html#transformers.PreTrainedModel.from_pretrained" rel="noreferrer">.from_pretrained</a> by setting the parameter <code>cache_dir</code>. You can also set a default location by exporting... | 450 |
transformers | Examples of Haskell Applicative Transformers | https://stackoverflow.com/questions/12587195/examples-of-haskell-applicative-transformers | <p>The wiki on www.haskell.org tells us the following about Applicative Transformers:</p>
<blockquote>
<p>So where are applicative transformers? The answer is, that we do not need special transformers for applicative functors since they can be combined in a generic way.
<a href="http://www.haskell.org/haskellwiki... | <p>The wiki article says that <code>liftA2 (<*>)</code> can be used to compose applicative functors. It's easy to see how to use it from its type:</p>
<pre><code>o :: (Applicative f, Applicative f1) =>
f (f1 (a -> b)) -> f (f1 a) -> f (f1 b)
o = liftA2 (<*>)
</code></pre>
<p>So to if <cod... | 451 |
transformers | Transformers: AutoModel from pretrained istantiation error | https://stackoverflow.com/questions/78566180/transformers-automodel-from-pretrained-istantiation-error | <p>I'm instantiating a CodeBert Model using AutoModel.fromPretrained.</p>
<pre><code>File "/public.hpc/codeBertConcat/./codeBertConcatEvaluation.py", line 278, in <module>
model = CodeBERTConcatenatedClass(num_classes=NUM_CLASSES).to(DEVICE)
File "/public.hpc/codeBertConcat/./codeBertConcatEv... | <p>Please check your computer supporting the GPU or using gpu first.</p>
<p>then If you do not resolve the problem, <code>upgrade pytorch version newest</code>.</p>
<p>your pytorch version is 1.8.1, current latest pytorch version is 2.3.0.
<a href="https://pytorch.org/get-started/locally/" rel="nofollow noreferrer">pyt... | 452 |
transformers | How to use transformers from nodejs script | https://stackoverflow.com/questions/73549859/how-to-use-transformers-from-nodejs-script | <p>I would like to use transformers in my Python code from NodeJs but it is not working without showing any error. Just by importing transformers my code isn't working. Of course by removing that part, the code runs smoothly.</p>
<p>NodeJs code</p>
<pre><code>const spawn = require("child_process").spawn;
con... | <p>Python usually gives errors but Python3 always get the job done. Although Python also has transformers package, it did not run in this instance. So replacing "python" with "python3" in the spawn process in nodeJs code worked like a charm.</p>
| 453 |
transformers | Use huggingface transformers without IPyWidgets | https://stackoverflow.com/questions/66644432/use-huggingface-transformers-without-ipywidgets | <p>I am trying to use the huggingface transformers library in a hosted Jupyter notebook platform called Deepnote. I want to download a model through the pipeline class but unfortunately deepnote does not support IPyWidgets. Is there a way to disable IPywidgets when using transformers? Specifically the below command.</p... | <p>You have to disable transformers logging. Even though it is possible to use <a href="https://huggingface.co/transformers/main_classes/logging.html#transformers.logging.set_verbosity" rel="noreferrer">transformers.logging.set_verbosity</a> to change the log level, it's not possible to set it to <code>logging.NOTSET</... | 454 |
transformers | Python transformers can't load | https://stackoverflow.com/questions/79130386/python-transformers-cant-load | <p>I have this code:</p>
<pre><code>from flask import Flask, request, jsonify
from flask_cors import CORS
from transformers import pipeline
app = Flask(__name__)
CORS(app)
model = pipeline("text-generation", model="MBZUAI-Paris/Atlas-Chat-9B")
@app.route('/generate', methods=['POST'])
def generate... | <p>It seems like your laptop does not have a dedicated GPU and has a RAM of 16 GB based on the specs for the model name. <em>I might be wrong here, but I am going to assume this configuration and write the answer.</em></p>
<p>The model you are trying to use is <strong>~19 GB</strong> which does not fit on your RAM. Usi... | 455 |
transformers | from transformers import AutoTokenizer, AutoModel | https://stackoverflow.com/questions/75991822/from-transformers-import-autotokenizer-automodel | <p>I am running this code:</p>
<p>I have these updated packages versions:
tqdm-4.65.0 transformers-4.27.4</p>
<p>I am running this code:
from transformers import AutoTokenizer, AutoModel</p>
<p>I am obtaining this erros:
ImportError: cannot import name 'ObjectWrapper' from 'tqdm.utils' (/Users/anitasancho/opt/anaconda3... | <p>I solved from the terminal window by:
Create a new virtual environment using <code>conda</code> with the following command:</p>
<pre><code>conda create --name mi_entorno python=3.7
</code></pre>
<p>Then, activate the virtual environment with the following command:</p>
<pre><code>conda activate mi_entorno
</code></pr... | 456 |
transformers | Installing `transformers` on HPC Cluster | https://stackoverflow.com/questions/62995253/installing-transformers-on-hpc-cluster | <p>I'm trying to install the transformers library on HPC. I do:</p>
<pre><code>git clone https://github.com/huggingface/transformers.git
cd transformers
pip install -e . --user
</code></pre>
<p>All three of these work as expected, with the last output being:</p>
<pre><code>Successfully installed dataclasses-0.7 numpy-1... | 457 | |
transformers | Consistent error message when using transformers | https://stackoverflow.com/questions/78954987/consistent-error-message-when-using-transformers | <p>I have been getting this error message for days on different projects and still can't understand where its from. This seems to only happen when I use tensorflow and transformers together. Can't really find anything for this specific error so help would be greatly appreciated. Am pretty new to this stuff.</p>
<pre><c... | 458 | |
transformers | Unable to import Hugging Face transformers | https://stackoverflow.com/questions/65383059/unable-to-import-hugging-face-transformers | <p>I have been using transformers fine up until today. However, when I imported the package today, I received this error message:</p>
<pre><code>In Transformers v4.0.0, the default path to cache downloaded models changed from '~/.cache/torch/transformers' to '~/.cache/huggingface/transformers'. Since you don't seem to ... | <p>As it appears to be a cache file, simply move the /huggingface/ dir to /huggingface.bak</p>
<p>Then you should be able to re-run the script.</p>
| 459 |
transformers | Why are monad transformers different to stacking monads? | https://stackoverflow.com/questions/38710154/why-are-monad-transformers-different-to-stacking-monads | <p>In many cases, it isn't clear to me what is to be gained by combining two monads with a transformer rather than using two separate monads. Obviously, using two separate monads is a hassle and can involve do notation inside do notation, but are there cases where it just isn't expressive enough?</p>
<p>One case seems... | <p>To answer you question about the difference between <code>Writer w (Maybe a)</code> vs <code>MaybeT (Writer w) a</code>, let's start by taking a look at the definitions:</p>
<pre><code>newtype WriterT w m a = WriterT { runWriterT :: m (a, w) }
type Writer w = WriterT w Identity
newtype MaybeT m a = MaybeT { runMay... | 460 |
transformers | Why use multi-headed attention in Transformers? | https://stackoverflow.com/questions/66244123/why-use-multi-headed-attention-in-transformers | <p>I am trying to understand why transformers use multiple attention heads. I found the following <a href="https://towardsdatascience.com/simple-explanation-of-transformers-in-nlp-da1adfc5d64f" rel="noreferrer">quote</a>:</p>
<blockquote>
<p>Instead of using a single attention function where the attention can
be domina... | <p>Multi-headed attention was introduced due to the observation that different words relate to each other in different ways. For a given word, the other words in the sentence could act as moderating or negating the meaning, but they could also express relations like inheritance (is a kind of), possession (belongs to), ... | 461 |
transformers | Equivalent to tokenizer() in Transformers 2.5.0? | https://stackoverflow.com/questions/73127139/equivalent-to-tokenizer-in-transformers-2-5-0 | <p>I am trying to convert the following code to work with Transformers 2.5.0. As written, it works in version 4.18.0, but not 2.5.0.</p>
<pre><code># Converting pretrained BERT classification model to regression model
# i.e. extracting base model and swapping out heads
from transformers import BertTokenizer, BertModel... | <p>Sadly their documentation for the old versions is broken, but you can use encode_plus as shown in the following (he oldest available documentation of encode_plus is from <a href="https://huggingface.co/transformers/v2.10.0/main_classes/tokenizer.html#transformers.PreTrainedTokenizer.encode_plus" rel="nofollow norefe... | 462 |
transformers | Unable to pip install -U sentence-transformers | https://stackoverflow.com/questions/61994001/unable-to-pip-install-u-sentence-transformers | <p>I am unable to do: pip install -U sentence-transformers. I get this message on Anaconda Prompt:
ERROR: Could not find a version that satisfies the requirement torch>=1.0.1 (from sentence-transformers) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No matching distribution found for torch>=1.0.1 (from senten... | <p>I tried to Conda Install pytorch and then installed Sentence Transformer by doing these steps: </p>
<ol>
<li><p>conda install pytorch torchvision cudatoolkit=10.0 -c pytorch</p></li>
<li><p>pip install -U sentence-transformers</p></li>
</ol>
<p>This worked.
Thanks</p>
| 463 |
transformers | Understanding monad transformers in Scala | https://stackoverflow.com/questions/44868593/understanding-monad-transformers-in-scala | <p>I'm trying to understand how to use Monad Transformers. I read the <a href="https://en.wikibooks.org/wiki/Haskell/Monad_transformers" rel="noreferrer">wiki article</a> about it and still have some questions.</p>
<p>We have <code>IO</code> monad that needs to read input from user. But the input is not always provide... | <p>Right, the way monad transformers work is to help you on working with a "inner" monad that is being "transformed" by a "outer" monad.</p>
<p>So <code>F[Option[A]</code> can be turned into a <code>OptionT[F, A]</code> (where <code>F</code> is any monad), which is much easier to work with.</p>
<p>About <code>ListT</... | 464 |
transformers | Laravel 5.1, Dingo - Nested Transformers | https://stackoverflow.com/questions/31507673/laravel-5-1-dingo-nested-transformers | <p>Is there an elegant way to nest transformers for relationship use? I'm looking to build a REST interface that allows for collections to conditionally include relationship models. So far I've been marginally successful, but it seems to break down a bit when it comes to the transformers (I'll admit I'm a bit new to ... | <p>I was able to find the answer to my question here: <a href="http://fractal.thephpleague.com/transformers/" rel="nofollow">http://fractal.thephpleague.com/transformers/</a>.</p>
| 465 |
transformers | Issue Installing transformers==4.18.0.dev0 from environment.yml File | https://stackoverflow.com/questions/77897628/issue-installing-transformers-4-18-0-dev0-from-environment-yml-file | <p>I created a virtual environment from the environment.yml file, and all packages were installed successfully except for the 'transformers' package. The requirement is to install 'transformers==4.18.0.dev0', but when I run the command:</p>
<blockquote>
<p><code>$pip install transformers==4.18.0.dev0</code></p>
</block... | <p>You appear to be using the wrong command. To install transformers 4.18.0, you should run <code>pip install transformers==4.18.0</code> and this version is compatible with python 3.6-3.9. See
<a href="https://pypi.org/project/transformers/4.18.0/" rel="nofollow noreferrer">https://pypi.org/project/transformers/4.18.0... | 466 |
transformers | Proper use of transformers vs interceptors | https://stackoverflow.com/questions/26387868/proper-use-of-transformers-vs-interceptors | <p>When POSTing to an endpoint in a service layer to update a user's profile, I need to strip certain values from the request payload (the profile with the desired modifications from the client) and re-attach them in the response payload (the updated profile from the server). I am currently performing behavior using A... | <p>I think your solution is fine but if you want an alternative, you can intercept specific requests like so. HTTP interceptors are mostly useful for handling global HTTP requests/responses (auth, error handling, etc.).</p>
<p>In any case, the "response" payload should be taken cared of from the API/server-side.</p>
... | 467 |
transformers | Transformation under Transformers | https://stackoverflow.com/questions/16552316/transformation-under-transformers | <p>I'm having a bit of difficulty with monad transformers at the moment. I'm defining a few different non-deterministic relations which make use of transformers. Unfortunately, I'm having trouble understanding how to translate cleanly from one effectful model to another.</p>
<p>Suppose these relations are "foo" and ... | <p>I think convert is a good answer, and using <code>Control.Monad.Morph</code> and <code>Control.Monad.Trans.Either</code> it's (almost) really simple to write:</p>
<pre><code>convert :: (Monad m, Functor m, MFunctor t)
=> (e -> e')
-> t (EitherT e m) b -> t (EitherT e' m) b
convert ... | 468 |
transformers | Type Variable Location in Transformers | https://stackoverflow.com/questions/49587122/type-variable-location-in-transformers | <p>Consider the <code>State</code> type - or at least a simplified version:</p>
<pre><code>newtype State s a = State { runState :: s -> (a, s) }
</code></pre>
<p>Now, let's say we want to derive the <code>StateT</code> monad transformer. <code>transformers</code> defines it as follows:</p>
<pre><code>newtype Stat... | <p>I think the difference can be easily understood when <code>m ~ IO</code>:</p>
<pre><code>s -> IO (a, s)
</code></pre>
<p>is the type of an action which can read the current state <code>s</code>, perform IO depending on that (e.g. printing the current state, reading a line from the user), and then produce both t... | 469 |
transformers | AttributeError: module transformers has no attribute TFGPTNeoForCausalLM | https://stackoverflow.com/questions/68604289/attributeerror-module-transformers-has-no-attribute-tfgptneoforcausallm | <p>I cloned this repository/documentation <a href="https://huggingface.co/EleutherAI/gpt-neo-125M" rel="nofollow noreferrer">https://huggingface.co/EleutherAI/gpt-neo-125M</a></p>
<p>I get the below error whether I run it on google collab or locally. I also installed transformers using this</p>
<pre><code>pip install g... | <p>My solution was to first edit the source code to remove the line that adds "TF" in front of the package as the correct transformers module is GPTNeoForCausalLM
, but somewhere in the source code it manually added a "TF" in front of it.</p>
<p>Secondly, before cloning the repository it is a must t... | 470 |
transformers | Monad Stack Penetration Classes with Free/Operational Monad Transformers? | https://stackoverflow.com/questions/17936900/monad-stack-penetration-classes-with-free-operational-monad-transformers | <p>Can there be mtl-like mechanism for monad transformers created by FreeT / ProgramT ?</p>
<p>My understanding of the history is as follows. Once upon a time monad transformer was invented. Then people started to stack monad transformers one on other, then found it annoying to insert <code>lift</code> everywhere. The... | <p>I tried a bit different approach, which gives at least a partial answer. Since stacking monads can be sometimes problematic, and we know all our monads are constructed from some data type, I tried instead to combine the data types.</p>
<p>I feel more comfortable with <code>MonadFree</code> so I used it, but I suppo... | 471 |
transformers | How to pass in transformers to ts-node? | https://stackoverflow.com/questions/57342857/how-to-pass-in-transformers-to-ts-node | <p>I'm trying to roll my own compiler for Typescript due to the fact that I need to use transformers.</p>
<p>We use ts-node to run some files (individual tests, etc.) and I also need the transformers to get passed in to the ts-node compiler.</p>
<p>Here's my code</p>
<pre><code>const ts = require('typescript');
cons... | <p>The <code>transformers</code> option to <code>register()</code> is of the <code>CustomTransformers</code> type (not an array as you're passing):</p>
<pre><code> interface CustomTransformers {
/** Custom transformers to evaluate before built-in .js transformations. */
before?: (TransformerFactory&... | 472 |
transformers | Grails :Column transformers ( like Hibernate ) | https://stackoverflow.com/questions/20430940/grails-column-transformers-like-hibernate | <p>I want to add <strong>Column transformers (read and write)</strong> <a href="https://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-column-read-and-write" rel="nofollow">like this:</a> to a Groovy domain class in a Grails application</p>
| <p>Depending on what you are trying to accomplish you could use Hibernate Custom Types which is explained in the Grails Documentation (<a href="http://grails.org/doc/latest/guide/GORM.html#customHibernateTypes" rel="nofollow">http://grails.org/doc/latest/guide/GORM.html#customHibernateTypes</a>). There is also a great... | 473 |
transformers | Confused about Haskell Monad Transformers | https://stackoverflow.com/questions/51864209/confused-about-haskell-monad-transformers | <p>I am confused about where <code>m</code> should be placed on the right side of the Monad transformers?</p>
<p>For example:</p>
<p><code>WriterT</code> is defined as</p>
<pre><code>newtype WriterT w m a = WriterT { runWriterT :: m (a, w) }
</code></pre>
<p>while <code>ReaderT</code> is defined as</p>
<pre><code>... | <p>The placement of the monad <code>m</code> will depend on the function and operation of the monad transformer that's being applied to the underlying monad <code>m</code>, so it's determined by what functionality the reader and writer are supposed to be adding to the monad.</p>
<p>It helps to remember that <code>runR... | 474 |
transformers | SentenceTransformerEmbeddings without installing sentence transformers | https://stackoverflow.com/questions/78613151/sentencetransformerembeddings-without-installing-sentence-transformers | <p>I had my langchain project working on my win10 laptop, but after moving it to Debian GNU/Linux 12 server, I've learned that I can't install sentence transformers (python 3.11) in realation to problems with installing torch.</p>
<p>Is there some alternative to SentenceTransformerEmbeddings without sentence transform... | 475 | |
transformers | ImportError: cannot import name 'BigBirdTokenizer' from 'transformers' (/usr/local/lib/python3.7/dist-packages/transformers/__init__.py) | https://stackoverflow.com/questions/69649310/importerror-cannot-import-name-bigbirdtokenizer-from-transformers-usr-loc | <p>In my env(colab) I need the following library.
Here is the list :</p>
<pre><code>!pip install --quiet transformers==4.1.1
!pip install --quiet pytorch-lightning==1.1.3
#!pip install pytorch-lightning
!pip install --quiet tokenizers==0.9.4
!pip install --quiet sentencepiece==0.1.94
!pip install torchtext==0.8.0 torch... | <p>I couldn't reproduce the error with the current master branch of haystack although I executed the exact same steps as mentioned in the question.</p>
<p>If you are still facing this issue, I suggest to start with a fresh virtual environment and check that you are really installing in that environment from the current... | 476 |
transformers | fail to use transformers to load model locally | https://stackoverflow.com/questions/79169173/fail-to-use-transformers-to-load-model-locally | <p>I have used the transformers function to download the whole model
into local directory: /home/marcus/Desktop/project/OCR_transformer_practices/models/moondream2
by the following code:</p>
<pre><code>from huggingface_hub import snapshot_download
# Specify the model ID and revision
model_id = "vikhyatk/moondream... | 477 | |
transformers | How to use the HuggingFace transformers pipelines? | https://stackoverflow.com/questions/60209265/how-to-use-the-huggingface-transformers-pipelines | <p>I'm trying to do a simple text classification project with Transformers, I want to use the pipeline feature added in the V2.3, but there is little to no documentation.</p>
<pre><code>data = pd.read_csv("data.csv")
FLAUBERT_NAME = "flaubert-base-cased"
encoder = LabelEncoder()
target = encoder.fit_transform(data["c... | 478 | |
transformers | Unable to user pipeline module inside transformers library | https://stackoverflow.com/questions/77814471/unable-to-user-pipeline-module-inside-transformers-library | <p>I have an issue. I'm using Python 3.11 and I have the latest version of transformers 4.36.2</p>
<p>The issue is that when I'm importing the pipeline module I facing the following issue in Jupyter Notebook:</p>
<pre><code>RuntimeError: Failed to import transformers.pipelines because of the following error (look up to... | <p>Can you try installing the latest version of <code>wrapt</code></p>
<pre><code>python -m pip install wrapt==1.16.0
</code></pre>
| 479 |
transformers | ImportError: cannot import name 'LLaMATokenizer' from 'transformers' | https://stackoverflow.com/questions/75907910/importerror-cannot-import-name-llamatokenizer-from-transformers | <p>I am not able to import <strong>LLaMATokenizer</strong></p>
<p>Any solution for this problem?</p>
<p>I am using the code of this repo.
<a href="https://github.com/zphang/transformers/tree/llama_push" rel="noreferrer">https://github.com/zphang/transformers/tree/llama_push</a>
and trying to load the models and tokeniz... | <p>To complement <a href="https://stackoverflow.com/users/6664872/cronoik">cronoik</a> answer (that is the correct answer):</p>
<p>If you still having problems with <code>from transformers import LlamaForCausalLM, LlamaTokenizer</code> try to install the package directly from github:</p>
<pre><code>pip install git+http... | 480 |
transformers | Simple Transformers producing nothing? | https://stackoverflow.com/questions/71200243/simple-transformers-producing-nothing | <p>I have a simple transformers script looking like this.</p>
<pre><code>from simpletransformers.seq2seq import Seq2SeqModel, Seq2SeqArgs
args = Seq2SeqArgs()
args.num_train_epoch=5
model = Seq2SeqModel(
"roberta",
"roberta-base",
"bert-base-cased",
)
import pandas as pd
df = p... | <p>Use this model instead.</p>
<pre><code>model = Seq2SeqModel(
encoder_decoder_type="marian",
encoder_decoder_name="Helsinki-NLP/opus-mt-en-mul",
args=args,
use_cuda=True,
)
</code></pre>
<p>roBERTa is not a good option for your task.</p>
<p>I have rewritten your code on <a href="ht... | 481 |
transformers | How to use SuperGLUE with huggingface-transformers | https://stackoverflow.com/questions/61043681/how-to-use-superglue-with-huggingface-transformers | <p>I would like to use SuperGLUE tasks with huggingface-transformers. Looking at this page:</p>
<p><a href="https://github.com/huggingface/transformers/blob/master/examples/README.md" rel="nofollow noreferrer">https://github.com/huggingface/transformers/blob/master/examples/README.md</a></p>
<p>The only useful script... | 482 | |
transformers | Disable default typescript transformers | https://stackoverflow.com/questions/55514236/disable-default-typescript-transformers | <p>I want to write a custom transpiler using the typescript transformer api that outputs typescript instead of javascript. To accomplish this I would need to disable the default transformers (typescript → ecma2017 → ecma2016 → ...).</p>
<p>Is this possible? I would prefer to use <code>tsc</code> directly, but if I hav... | <p>There's no <code>ts.ScriptTarget.TypeScript</code> so you'll need to use the compiler API.</p>
<p>Here's the basic idea (not tested, but should help you start on this):</p>
<pre><code>import * as ts from "typescript";
// setup
const printer = ts.createPrinter();
const sourceFiles: ts.SourceFile[] = ...;
const tra... | 483 |
transformers | Monad Transformers in Scala | https://stackoverflow.com/questions/40503324/monad-transformers-in-scala | <p>I have been trying simple Monad Transformers where I have for comprehensions involving <code>M[F[A]]</code> where <code>M</code> and <code>F</code> are monads. How can I make <code>M[F[A]]</code> and <code>M[S[A]]</code> work together in a for comp if <code>S</code> is a different monad? </p>
<p>For example:</p>
<... | <p>Monad Transformers help you in composing two values of type <code>F[G[X]]</code>.</p>
<p>In other terms, monad transformers work with <code>F[G[X]]</code> because they leverage the fact that you know how to compose two <code>G[X]</code> if <code>Monad[G]</code> exists.</p>
<p>Now, in case of <code>F[G[X]</code> an... | 484 |
transformers | Error while installing sentence-transformers | https://stackoverflow.com/questions/78001556/error-while-installing-sentence-transformers | <p>Get the following error while installing sentence-transformers on Windows 11 (using the latest version of Python and pip). Can someone please help with this? Checked many other similar posts, but none of those solutions work.</p>
<pre><code>C:\Users\abc\ai\llama\jupyterproj\stlit>py -m pip install sentence-transf... | <p>You need to use <code>python 3.11</code> to install <code>sentence-transformers</code></p>
<p>It is dependent on pytorch</p>
<p><strong><a href="https://pytorch.org/get-started/locally/#windows-python" rel="nofollow noreferrer">https://pytorch.org/get-started/locally/#windows-python</a></strong></p>
<blockquote>
<p>... | 485 |
transformers | Monad Transformers in C# | https://stackoverflow.com/questions/20353256/monad-transformers-in-c | <p>I am working on using monad transformers in C#.<br>
I would like to know if the following code I present, shows that I have understood this.<br>
I am fairly new to this so any feedback / comments are really welcome.<br>
This example is just for wrapping a maybe monad in a validation monad.</p>
<pre><code>using Syst... | <p>Almost, is the quickest answer. Your <code>ValidationMaybeT</code> is storing the value of the <code>Maybe</code>, whereas a true monad transformer would have the behaviour of the <code>Maybe</code> and the <code>Validation</code> monad, and could modify the default behaviour of the wrapped monad if required. </p>... | 486 |
transformers | Loading a safetensor file in transformers | https://stackoverflow.com/questions/76247802/loading-a-safetensor-file-in-transformers | <p>I have downloaded this <a href="https://huggingface.co/TheBloke/vicuna-13B-1.1-GPTQ-4bit-128g" rel="nofollow noreferrer">model</a> from huggingface. I am trying to load this model in transformers so I can do inferencing:</p>
<pre><code>from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTok... | <p>you need to tell it to look for the safetensors</p>
<pre><code>AutoModelForCausalLM.from_pretrained(
<path>,
use_safetensors=True,
<rest_of_args>
)
</code></pre>
<p>This assumes you have the safetensors weights map in the same folder ofc</p>
<pre><code>model.safetensors.index.json
</code></pr... | 487 |
transformers | What is difference between those two monad transformers? | https://stackoverflow.com/questions/36671136/what-is-difference-between-those-two-monad-transformers | <p>I'm familiar with monads, e.g. <code>Reader</code>, <code>Error</code>, and <code>State</code>. Transformers, however, are very new to me, hence this question.</p>
<p>Intuitively, I can tell there is a difference between the following two monad transformers, but I can't quite pinpoint what it is...</p>
<pre><code>... | <p>To simplify, compare only the relevant part (which isn't trivially the same):</p>
<pre><code>MaybeT (StateT Integer Identity) a
StateT Integer (MaybeT Identity) a
</code></pre>
<p>We know that (ignoring the <code>newtype</code> abstractions)</p>
<pre><code>type MaybeT m a = m (Maybe a)
type StateT s m a = s ->... | 488 |
transformers | Chatbot using Huggingface Transformers | https://stackoverflow.com/questions/70055966/chatbot-using-huggingface-transformers | <p>I would like to use Huggingface Transformers to implement a chatbot. Currently, I have the code shown below. The transformer model already takes into account the history of past user input.</p>
<p>Is there something else (additional code) I have to take into account for building the chatbot?</p>
<p>Second, how can I... | <p>Here is an example of using the <code>DialoGPT</code> model with Tensorflow:</p>
<pre class="lang-py prettyprint-override"><code>from transformers import TFAutoModelForCausalLM, AutoTokenizer, BlenderbotTokenizer, TFBlenderbotForConditionalGeneration
import tensorflow as tf
chat_bots = {
'BlenderBot': [Blenderb... | 489 |
transformers | sklearn ColumnTransformer: Duplicate columns in transformers | https://stackoverflow.com/questions/63475704/sklearn-columntransformer-duplicate-columns-in-transformers | <p>I am looking for a help building a data preprocessing pipleline using sklearn's ColumnTransformer functions.</p>
<p>Currently my pipleline looks something like this:</p>
<pre><code>from scipy.stats.mstats import winsorize
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
Colum... | <p>From what I understand, you can use two <code>ColumnTransformer</code> and one <code>FeatureUnion</code> to achieve what you want. One <code>ColumnTransformer</code> will have <code>remainder='passthrough'</code> to keep all columns except the ones being transformed, and the other will have <code>remainder='drop'</c... | 490 |
transformers | Pyspark: save transformers | https://stackoverflow.com/questions/36136662/pyspark-save-transformers | <p>I am using some transformers of Pyspark such as StringIndexer, StandardScaler and more. I first apply those to the training set and then later on I want to use the same transformation objects (same parameters of StringIndexerModel, StandardScalerModel) in order to apply them on the test set. Therefore, I am looking ... | <p>I found an easy solution.</p>
<p>Save the indexer model to a file (on HDFS). </p>
<pre><code>writer = indexerModel._call_java("write")
writer.save("indexerModel")
</code></pre>
<p>Load the indexer model from a file (saved on HDFS). </p>
<pre><code>indexer = StringIndexerModel._new_java_obj("org.apache.spark.m... | 491 |
transformers | Higher Accuracy using SimpleTransformers vs Transformers Library with BERT | https://stackoverflow.com/questions/64595546/higher-accuracy-using-simpletransformers-vs-transformers-library-with-bert | <p>I am working on a project for text classification using BERT</p>
<p>I am getting ca. 90% accuracy by using simple transformers.
But I only get like 60% using my own training for-loop (not published here) or using the trainer module from the transformers library.
Both are done with the default parameters of simple tr... | 492 | |
transformers | Hugging-Face Transformers: Loading model from path error | https://stackoverflow.com/questions/62641972/hugging-face-transformers-loading-model-from-path-error | <p>I am pretty new to Hugging-Face transformers. I am facing the following issue when I try to load <strong>xlm-roberta-base</strong> model from a given path:</p>
<pre><code>>> tokenizer = AutoTokenizer.from_pretrained(model_path)
>> Traceback (most recent call last):
File "<stdin>", line ... | <p>I assume you have created that directory as described in the <a href="https://huggingface.co/transformers/main_classes/configuration.html#transformers.PretrainedConfig.save_pretrained" rel="nofollow noreferrer">documentation</a> with :</p>
<pre class="lang-py prettyprint-override"><code>tokenizer.save_pretrained('YO... | 493 |
transformers | Monad vs Monad transformers | https://stackoverflow.com/questions/45082178/monad-vs-monad-transformers | <p>"Monads allow the programmer to build up computations using sequential building blocks" therefore it allows us to combine some computations. If this is the case, then why the following code can not be run? </p>
<pre><code>import Control.Monad.Trans.State
gt :: State String String
gt = do
name <- get
putSt... | <p>Monad transformers <em>are</em> the mechanisms for putting different functions in a monad.</p>
<p>A monad only knows how to combine computations that are within the abilities of that monad. You can't do I/O in a <code>State</code> monad, but you can in a <code>StateT s IO a</code> monad. However, you will need to u... | 494 |
transformers | Monad Transformers and lift function | https://stackoverflow.com/questions/17204573/monad-transformers-and-lift-function | <p>Why isn't it necessary to use lift for executing a function in an internal monad transformer environment, except for IO? I mean, if I have StateT over WriterT and WriterT over ReaderT, why can I do this?</p>
<pre><code>tell $ {- any code here for the Writer -}
foo <- asks {- This for the reader -}
and so on...
<... | <p>It's because the Monad Transformer Library (MTL) recognizes that it's quite common for you to stack monads in just that way so they don't define <code>tell</code> as just some function <code>(Mondoid w) => w -> Writer ()</code>. </p>
<p>Instead they have <a href="http://hackage.haskell.org/packages/archive/mt... | 495 |
transformers | Fine-tuning BERT on SequenceClassification using Transformers framework | https://stackoverflow.com/questions/64805769/fine-tuning-bert-on-sequenceclassification-using-transformers-framework | <p>I am currently fine-tuning a BERT model on a sequence classification task. To do this, I am using the transformers framework. This requires a Batch input in a Trainer: <a href="https://huggingface.co/transformers/_modules/transformers/trainer.html" rel="nofollow noreferrer">https://huggingface.co/transformers/_modul... | 496 | |
transformers | Repo id error when using hugging face transformers | https://stackoverflow.com/questions/76900349/repo-id-error-when-using-hugging-face-transformers | <p>I keep getting this error when I try to use hugging face transformers library.</p>
<pre><code>huggingface_hub.utils._validators.HFValidationError: Repo id must be in the form 'repo_name' or 'namespace/repo_name': 'C:/Users/FZH91R/PycharmProjects/DudeWheresMyHealing/Pytorch/tf_model.h5'. Use `repo_type` argument if n... | 497 | |
transformers | Monad transformers explained in Javascript? | https://stackoverflow.com/questions/42783479/monad-transformers-explained-in-javascript | <p>I'm having a hard time understanding monad transformers, partly because most examples and explanations use Haskell.</p>
<p>Could anyone give an example of creating a transformer to merge a Future and an Either monad in Javascript and how it can be used.</p>
<p>If you can use the <code>ramda-fantasy</code> implemen... | <p><strong>Rules first</strong></p>
<p>First we have the <em>Natural Transformation Law</em></p>
<ul>
<li>Some functor <code>F</code> of <code>a</code>, mapped with function <code>f</code>, yields <code>F</code> of <code>b</code>, then naturally transformed, yields some functor <code>G</code> of <code>b</code>.</li>
... | 498 |
transformers | Cannot import "from transformers import Wav2Vec2Processor" | https://stackoverflow.com/questions/76753228/cannot-import-from-transformers-import-wav2vec2processor | <p>The libraries used<br />
python : 3.7.16<br />
transformers : 4.24.0<br />
tensorflow : 2.4.1</p>
<p>I am triyng to convert tensorflow wav2vec model into tflite in colab</p>
<p><code>from transformers import Wav2Vec2Processor</code>
for this line it gives a error cannot load the wav2vec2Processor.
<code>from transfo... | <p>at first Update transformers to the latest version:</p>
<pre><code>!pip install transformers --upgrade
</code></pre>
<p>Check dependencies: like your Error <code>No module named 'tokenizers.tokenizers'</code></p>
<pre><code>!pip install tokenizers
</code></pre>
<p>after you install the dependencies Restart the runt... | 499 |
pytorch | How do I check if PyTorch is using the GPU? | https://stackoverflow.com/questions/48152674/how-do-i-check-if-pytorch-is-using-the-gpu | <p>How do I check if PyTorch is using the GPU? The <code>nvidia-smi</code> command can detect GPU activity, but I want to check it directly from inside a Python script.</p>
| <p>These functions should help:</p>
<pre><code>>>> import torch
>>> torch.cuda.is_available()
True
>>> torch.cuda.device_count()
1
>>> torch.cuda.current_device()
0
>>> torch.cuda.device(0)
<torch.cuda.device at 0x7efce0b03be0>
>>> torch.cuda.get_device_n... | 500 |
pytorch | How do I save a trained model in PyTorch? | https://stackoverflow.com/questions/42703500/how-do-i-save-a-trained-model-in-pytorch | <p>How do I save a trained model in PyTorch? I have read that:</p>
<ol>
<li><a href="https://github.com/torch/torch7/blob/master/doc/serialization.md#torchsavefilename-object--format-referenced" rel="noreferrer"><code>torch.save()</code></a>/<a href="https://github.com/torch/torch7/blob/master/doc/serialization.md#obje... | <p>Found <a href="https://github.com/pytorch/pytorch/blob/761d6799beb3afa03657a71776412a2171ee7533/docs/source/notes/serialization.rst" rel="noreferrer">this page</a> on their github repo:</p>
<blockquote>
<h4>Recommended approach for saving a model</h4>
<p>There are two main approaches for serializing and restoring a ... | 501 |
pytorch | How do I print the model summary in PyTorch? | https://stackoverflow.com/questions/42480111/how-do-i-print-the-model-summary-in-pytorch | <p>How do I print the summary of a model in PyTorch like what <code>model.summary()</code> does in Keras:</p>
<pre><code>Model Summary:
____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to ... | <p>While you will not get as detailed information about the model as in Keras' model.summary, simply printing the model will give you some idea about the different layers involved and their specifications.</p>
<p>For instance:</p>
<pre><code>from torchvision import models
model = models.vgg16()
print(model)
</code></pr... | 502 |
pytorch | What's the difference between `reshape()` and `view()` in PyTorch? | https://stackoverflow.com/questions/49643225/whats-the-difference-between-reshape-and-view-in-pytorch | <p>In numpy, we use <code>ndarray.reshape()</code> for reshaping an array.</p>
<p>I noticed that in PyTorch, people use <code>torch.view()</code> for the same purpose, but at the same time, there is also a <code>torch.reshape()</code> existing.</p>
<p>So I am wondering what the differences are between them and when I s... | <p><code>torch.view</code> has existed for a long time. It will return a tensor with the new shape. The returned tensor will share the underling data with the original tensor.
See the <a href="http://pytorch.org/docs/master/tensors.html?highlight=view#torch.Tensor.view" rel="noreferrer">documentation here</a>.</p>
<p... | 503 |
pytorch | Pytorch tensor to numpy array | https://stackoverflow.com/questions/49768306/pytorch-tensor-to-numpy-array | <p>I have a pytorch <code>Tensor</code> of shape <code>[4, 3, 966, 1296]</code>. I want to convert it to <code>numpy</code> array using the following code:</p>
<pre><code>imgs = imgs.numpy()[:, ::-1, :, :]
</code></pre>
<p>How does that code work?</p>
| <p>There are 4 dimensions of the tensor you want to convert.</p>
<pre><code>[:, ::-1, :, :]
</code></pre>
<p><code>:</code> means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.</p>
<p><code>::-1</code> means that for the second axes it reverses the th... | 504 |
pytorch | What does `view()` do in PyTorch? | https://stackoverflow.com/questions/42479902/what-does-view-do-in-pytorch | <p>What does <code>view()</code> do to the tensor <code>x</code>? What do negative values mean?</p>
<pre><code>x = x.view(-1, 16 * 5 * 5)
</code></pre>
| <p><code>view()</code> reshapes the tensor without copying memory, similar to numpy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="noreferrer"><code>reshape()</code></a>.</p>
<p>Given a tensor <code>a</code> with 16 elements:</p>
<pre><code>import torch
a = torch.range(1, 16)
<... | 505 |
pytorch | Check the total number of parameters in a PyTorch model | https://stackoverflow.com/questions/49201236/check-the-total-number-of-parameters-in-a-pytorch-model | <p>How do I count the total number of parameters in a PyTorch model? Something similar to <code>model.count_params()</code> in Keras.</p>
| <p>PyTorch doesn't have a function to calculate the total number of parameters as Keras does, but it's possible to sum the number of elements for every parameter group:</p>
<pre><code>pytorch_total_params = sum(p.numel() for p in model.parameters())
</code></pre>
<p>If you want to calculate only the <em>trainable</em> ... | 506 |
pytorch | PyTorch preferred way to copy a tensor | https://stackoverflow.com/questions/55266154/pytorch-preferred-way-to-copy-a-tensor | <p>There seems to be several ways to create a copy of a tensor in PyTorch, including</p>
<pre><code>y = tensor.new_tensor(x) #a
y = x.clone().detach() #b
y = torch.empty_like(x).copy_(x) #c
y = torch.tensor(x) #d
</code></pre>
<p><code>b</code> is explicitly preferred over <code>a</code> and <code>d</code> according... | <p><strong>TL;DR</strong></p>
<p>Use <code>.clone().detach()</code> (or preferrably <code>.detach().clone()</code>)</p>
<blockquote>
<p>If you first detach the tensor and then clone it, the computation path is not copied, the other way around it is copied and then abandoned. Thus, <code>.detach().clone()</code> is very... | 507 |
pytorch | Why do we need to call zero_grad() in PyTorch? | https://stackoverflow.com/questions/48001598/why-do-we-need-to-call-zero-grad-in-pytorch | <p>Why does <a href="https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html" rel="noreferrer"><code>zero_grad()</code></a> need to be called during training?</p>
<pre><code>| zero_grad(self)
| Sets gradients of all model parameters to zero.
</code></pre>
| <p>In <a href="https://github.com/pytorch/pytorch" rel="noreferrer"><code>PyTorch</code></a>, for every mini-batch during the <em>training</em> phase, we typically want to explicitly set the gradients to zero before starting to do backpropagation (i.e., updating the <em><strong>W</strong>eights</em> and <em><strong>b</... | 508 |
pytorch | L1/L2 regularization in PyTorch | https://stackoverflow.com/questions/42704283/l1-l2-regularization-in-pytorch | <p>How do I add L1/L2 regularization in PyTorch without manually computing it?</p>
| <p>See the <a href="http://pytorch.org/docs/optim.html#torch.optim.Adagrad" rel="noreferrer">documentation</a>. Add a <code>weight_decay</code> parameter to the optimizer for L2 regularization.</p>
| 509 |
pytorch | What does model.eval() do in pytorch? | https://stackoverflow.com/questions/60018578/what-does-model-eval-do-in-pytorch | <p>When should I use <code>.eval()</code>? I understand it is supposed to allow me to "evaluate my model". How do I turn it back off for training?</p>
<p>Example training <a href="https://github.com/natanielruiz/deep-head-pose/blob/master/code/train_hopenet.py" rel="noreferrer">code</a> using <code>.eval()</c... | <p><code>model.eval()</code> is a kind of switch for some specific layers/parts of the model that behave differently during training and inference (evaluating) time. For example, Dropouts Layers, BatchNorm Layers etc. You need to turn them off during model evaluation, and <code>.eval()</code> will do it for you. In add... | 510 |
pytorch | How to avoid "CUDA out of memory" in PyTorch | https://stackoverflow.com/questions/59129812/how-to-avoid-cuda-out-of-memory-in-pytorch | <p>I think it's a pretty common message for PyTorch users with low GPU memory:</p>
<pre><code>RuntimeError: CUDA out of memory. Tried to allocate X MiB (GPU X; X GiB total capacity; X GiB already allocated; X MiB free; X cached)
</code></pre>
<p>I tried to process an image by loading each layer to GPU and then loading ... | <p>Although</p>
<pre><code>import torch
torch.cuda.empty_cache()
</code></pre>
<p>provides a good alternative for clearing the occupied cuda memory and we can also manually clear the not in use variables by using,</p>
<pre><code>import gc
del variables
gc.collect()
</code></pre>
<p>But still after using these commands,... | 511 |
pytorch | What does "unsqueeze" do in Pytorch? | https://stackoverflow.com/questions/57237352/what-does-unsqueeze-do-in-pytorch | <p>The <a href="https://pytorch.org/docs/stable/generated/torch.unsqueeze.html" rel="noreferrer">PyTorch documentation</a> says:</p>
<blockquote>
<p>Returns a new tensor with a dimension of size one inserted at the specified position. [...]</p>
<pre><code>>>> x = torch.tensor([1, 2, 3, 4])
>>> torch.u... | <p>If you look at the shape of the array before and after, you see that before it was <code>(4,)</code> and after it is <code>(1, 4)</code> (when second parameter is <code>0</code>) and <code>(4, 1)</code> (when second parameter is <code>1</code>). So a <code>1</code> was inserted in the shape of the array at axis <cod... | 512 |
pytorch | Pytorch, what are the gradient arguments | https://stackoverflow.com/questions/43451125/pytorch-what-are-the-gradient-arguments | <p>I am reading through the documentation of PyTorch and found an example where they write </p>
<pre><code>gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
print(x.grad)
</code></pre>
<p>where x was an initial variable, from which y was constructed (a 3-vector). The question is, what are the 0.... | <blockquote>
<p>The original code I haven't found on PyTorch website anymore.</p>
</blockquote>
<pre><code>gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
print(x.grad)
</code></pre>
<p>The problem with the code above is there is no function based on how to calculate the gradients. This means we... | 513 |
pytorch | Data Augmentation in PyTorch | https://stackoverflow.com/questions/51677788/data-augmentation-in-pytorch | <p>I am a little bit confused about the data augmentation performed in PyTorch. Now, as far as I know, when we are performing data augmentation, we are KEEPING our original dataset, and then adding other versions of it (Flipping, Cropping...etc). But that doesn't seem like happening in PyTorch. As far as I understood f... | <p>The <code>transforms</code> operations are applied to your original images at every batch generation. So your dataset is left unchanged, only the batch images are copied and transformed every iteration.</p>
<p>The confusion may come from the fact that often, like in your example, <code>transforms</code> are used bo... | 514 |
pytorch | How do I visualize a net in Pytorch? | https://stackoverflow.com/questions/52468956/how-do-i-visualize-a-net-in-pytorch | <pre><code>import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.models as models
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.autograd import Variable
from torchvision.models.vgg import model_urls
from torchviz im... | <p>The <code>make_dot</code> expects a variable (i.e., tensor with <code>grad_fn</code>), not the model itself.<br />
try:</p>
<pre><code>x = torch.zeros(1, 3, 224, 224, dtype=torch.float, requires_grad=False)
out = resnet(x)
make_dot(out) # plot graph of variable, not of a nn.Module
</code></pre>
| 515 |
pytorch | How do I initialize weights in PyTorch? | https://stackoverflow.com/questions/49433936/how-do-i-initialize-weights-in-pytorch | <p>How do I initialize weights and biases of a network (via e.g. He or Xavier initialization)?</p>
| <h1>Single layer</h1>
<p>To initialize the weights of a single layer, use a function from <a href="https://pytorch.org/docs/master/nn.init.html" rel="noreferrer"><code>torch.nn.init</code></a>. For instance:</p>
<pre><code>conv1 = torch.nn.Conv2d(...)
torch.nn.init.xavier_uniform(conv1.weight)
</code></pre>
<p>Alternat... | 516 |
pytorch | How to do gradient clipping in pytorch? | https://stackoverflow.com/questions/54716377/how-to-do-gradient-clipping-in-pytorch | <p>What is the correct way to perform gradient clipping in pytorch?</p>
<p>I have an exploding gradients problem.</p>
| <p><a href="https://pytorch.org/docs/stable/generated/torch.nn.utils.clip_grad_norm_.html#torch.nn.utils.clip_grad_norm_" rel="noreferrer"><code>clip_grad_norm</code></a> (which is actually deprecated in favor of <code>clip_grad_norm_</code> following the more consistent syntax of a trailing <code>_</code> when in-plac... | 517 |
pytorch | What does .contiguous() do in PyTorch? | https://stackoverflow.com/questions/48915810/what-does-contiguous-do-in-pytorch | <p>What does <code>x.contiguous()</code> do for a tensor <code>x</code>?</p>
| <p>There are a few operations on Tensors in PyTorch that do not change the contents of a tensor, but change the way the data is organized. These operations include:</p>
<blockquote>
<p><code>narrow()</code>, <code>view()</code>, <code>expand()</code> and <code>transpose()</code></p>
</blockquote>
<p><em>For example:</e... | 518 |
pytorch | Convert PyTorch tensor to python list | https://stackoverflow.com/questions/53903373/convert-pytorch-tensor-to-python-list | <p>How do I convert a PyTorch <code>Tensor</code> into a python <code>list</code>?</p>
<p>I want to convert a tensor of size <code>[1, 2048, 1, 1]</code> into a list of 2048 elements. My tensor has floating point values. Is there a solution which also works with other data types such as int?</p>
| <p>Use <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.tolist" rel="noreferrer"><code>Tensor.tolist()</code></a> e.g:</p>
<blockquote>
<pre><code>>>> import torch
>>> a = torch.randn(2, 2)
>>> a.tolist()
[[0.012766935862600803, 0.5415473580360413],
[-0.08909505605697632, 0... | 519 |
pytorch | What does model.train() do in PyTorch? | https://stackoverflow.com/questions/51433378/what-does-model-train-do-in-pytorch | <p>Does it call <code>forward()</code> in <code>nn.Module</code>? I thought when we call the model, <code>forward</code> method is being used.
Why do we need to specify train()?</p>
| <p><code>model.train()</code> tells your model that you are training the model. This helps inform layers such as Dropout and BatchNorm, which are designed to behave differently during training and evaluation. For instance, in training mode, BatchNorm updates a moving average on each new batch; whereas, for evaluation m... | 520 |
pytorch | Why `torch.cuda.is_available()` returns False even after installing pytorch with cuda? | https://stackoverflow.com/questions/60987997/why-torch-cuda-is-available-returns-false-even-after-installing-pytorch-with | <p>On a Windows 10 PC with an NVidia GeForce 820M
I installed CUDA 9.2 and cudnn 7.1 successfully,
and then installed PyTorch using the instructions at pytorch.org:</p>
<pre><code>pip install torch==1.4.0+cu92 torchvision==0.5.0+cu92 -f https://download.pytorch.org/whl/torch_stable.html
</code></pre>
<p>But I get:</p>
... | <p>Your graphics card does not support CUDA 9.0.</p>
<p>Since I've seen a lot of questions that refer to issues like this I'm writing a broad answer on how to check if your system is compatible with CUDA, specifically targeted at using PyTorch with CUDA support. Various circumstance-dependent options for resolving issu... | 521 |
pytorch | How to multiply matrices in PyTorch? | https://stackoverflow.com/questions/44524901/how-to-multiply-matrices-in-pytorch | <p>With numpy, I can do a simple matrix multiplication like this:</p>
<pre><code>a = numpy.ones((3, 2))
b = numpy.ones((2, 1))
result = a.dot(b)
</code></pre>
<p>However, this does not work with PyTorch:</p>
<pre><code>a = torch.ones((3, 2))
b = torch.ones((2, 1))
result = torch.dot(a, b)
</code></pre>
<p>This code thr... | <p>Use <a href="https://pytorch.org/docs/stable/generated/torch.mm.html" rel="noreferrer"><code>torch.mm</code></a>:</p>
<pre><code>torch.mm(a, b)
</code></pre>
<p><code>torch.dot()</code> behaves differently to <code>np.dot()</code>. There's been some discussion about what would be desirable <a href="https://github.co... | 522 |
pytorch | PyTorch reshape tensor dimension | https://stackoverflow.com/questions/43328632/pytorch-reshape-tensor-dimension | <p>I want to reshape a vector of shape <code>(5,)</code> into a matrix of shape <code>(1, 5)</code>.</p>
<p>With numpy, I can do:</p>
<pre><code>>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5])
>>> a.shape
(5,)
>>> a = np.reshape(a, (1, 5))
>>> a.shape
(1, 5)
>>... | <p>Use <a href="https://pytorch.org/docs/stable/generated/torch.unsqueeze.html#torch.unsqueeze" rel="noreferrer"><code>torch.unsqueeze(input, dim, out=None)</code></a>:</p>
<pre><code>>>> import torch
>>> a = torch.Tensor([1, 2, 3, 4, 5])
>>> a
1
2
3
4
5
[torch.FloatTensor of size 5]
... | 523 |
pytorch | Pytorch Operation to detect NaNs | https://stackoverflow.com/questions/48158017/pytorch-operation-to-detect-nans | <p>
Is there a Pytorch-internal procedure to detect <code>NaN</code>s in Tensors? Tensorflow has the <code>tf.is_nan</code> and the <code>tf.check_numerics</code> operations ... Does Pytorch have something similar, somewhere? I could not find something like this in the docs... </p>
<p>I am looking specifically for a P... | <p>You can always leverage the fact that <code>nan != nan</code>:</p>
<pre><code>>>> x = torch.tensor([1, 2, np.nan])
tensor([ 1., 2., nan.])
>>> x != x
tensor([ 0, 0, 1], dtype=torch.uint8)
</code></pre>
<p>With pytorch 0.4 there is also <a href="https://pytorch.org/docs/stable/torch.html?high... | 524 |
pytorch | Pytorch vs. Keras: Pytorch model overfits heavily | https://stackoverflow.com/questions/50079735/pytorch-vs-keras-pytorch-model-overfits-heavily | <p>For several days now, I'm trying to replicate my keras training results with pytorch. Whatever I do, the pytorch model will overfit far earlier and stronger to the validation set then in keras. For pytorch I use the same XCeption Code from <a href="https://github.com/Cadene/pretrained-models.pytorch" rel="noreferrer... | <p>it may be because type of weight initialization you are using
otherwise this should not happen
try with same initializer in both the models</p>
| 525 |
pytorch | How to tell PyTorch to not use the GPU? | https://stackoverflow.com/questions/53266350/how-to-tell-pytorch-to-not-use-the-gpu | <p>I want to do some timing comparisons between CPU & GPU as well as some profiling and would like to know if there's a way to tell <a href="/questions/tagged/pytorch" class="post-tag" title="show questions tagged 'pytorch'" rel="tag">pytorch</a> to not use the GPU and instead use the CPU only? I realize I ... | <p>Before running your code, run this shell command to tell torch that there are no GPUs:</p>
<pre><code>export CUDA_VISIBLE_DEVICES=""
</code></pre>
<hr />
<p>This will tell it to use only one GPU (the one with id 0) and so on:</p>
<pre><code>export CUDA_VISIBLE_DEVICES="0"
</code></pre>
| 526 |
pytorch | Why is PyTorch called PyTorch? | https://stackoverflow.com/questions/51530778/why-is-pytorch-called-pytorch | <p>I have been looking into deep learning frameworks lately and have been wondering about the origin of the name of PyTorch.</p>
<p>With Keras, their <a href="https://keras.io/" rel="noreferrer">home page</a> nicely explains the name's origin, and with something like TensorFlow, the reasoning behind the name seems rath... | <p>Here a short answer, formed as another question:</p>
<h3>Torch, SMORCH ???</h3>
<p>PyTorch developed from Torch7. A precursor to the original Torch was a library called <a href="http://bengio.abracadoudou.com/SVMTorch.html" rel="noreferrer">SVM-Torch</a>, which was developed around 2001. The SVM stands for Support V... | 527 |
pytorch | pytorch - connection between loss.backward() and optimizer.step() | https://stackoverflow.com/questions/53975717/pytorch-connection-between-loss-backward-and-optimizer-step | <p>Where is an explicit connection between the <code>optimizer</code> and the <code>loss</code>?</p>
<p>How does the optimizer know where to get the gradients of the loss without a call liks this <code>optimizer.step(loss)</code>?</p>
<p>-More context-</p>
<p>When I minimize the loss, I didn't have to pass the gradient... | <p>Without delving too deep into the internals of pytorch, I can offer a simplistic answer:</p>
<p>Recall that when initializing <code>optimizer</code> you explicitly tell it what parameters (tensors) of the model it should be updating. The gradients are "stored" by the tensors themselves (they have a <a href... | 528 |
pytorch | Understanding PyTorch einsum | https://stackoverflow.com/questions/55894693/understanding-pytorch-einsum | <p>I'm familiar with how <a href="https://en.wikipedia.org/wiki/Einstein_notation" rel="noreferrer"><strong><code>einsum</code></strong></a> works in NumPy. A similar functionality is also offered by PyTorch: <a href="https://pytorch.org/docs/stable/torch.html#torch.einsum" rel="noreferrer"><strong>torch.einsum()</stro... | <p>Since the description of einsum is skimpy in torch documentation, I decided to write this post to document, compare and contrast how <a href="https://pytorch.org/docs/stable/_modules/torch/functional.html#einsum" rel="noreferrer"><code>torch.einsum()</code></a> behaves when compared to <a href="https://numpy.org/dev... | 529 |
pytorch | How do I convert a Pandas dataframe to a PyTorch tensor? | https://stackoverflow.com/questions/50307707/how-do-i-convert-a-pandas-dataframe-to-a-pytorch-tensor | <p>How do I train a simple neural network with PyTorch on a pandas dataframe <code>df</code>?</p>
<p>The column <code>df["Target"]</code> is the target (e.g. labels) of the network. This doesn't work:</p>
<pre><code>import pandas as pd
import torch.utils.data as data_utils
target = pd.DataFrame(df['Target'])... | <p>I'm referring to the question in the title as you haven't really specified anything else in the text, so just converting the DataFrame into a PyTorch tensor. </p>
<p>Without information about your data, I'm just taking float values as example targets here.</p>
<p><strong>Convert Pandas dataframe to PyTorch tensor?... | 530 |
pytorch | Differences in SciKit Learn, Keras, or Pytorch | https://stackoverflow.com/questions/54527439/differences-in-scikit-learn-keras-or-pytorch | <p>Are these libraries fairly interchangeable?</p>
<p>Looking here, <a href="https://stackshare.io/stackups/keras-vs-pytorch-vs-scikit-learn" rel="noreferrer">https://stackshare.io/stackups/keras-vs-pytorch-vs-scikit-learn</a>, it seems the major difference is the underlying framework (at least for PyTorch).</p>
| <p>Yes, there is a major difference.</p>
<p>SciKit Learn is a general machine learning library, built on top of NumPy. It features a lot of machine learning algorithms such as support vector machines, random forests, as well as a lot of utilities for general pre- and postprocessing of data. It is not a neural network ... | 531 |
pytorch | How can l uninstall PyTorch with Anaconda? | https://stackoverflow.com/questions/43664444/how-can-l-uninstall-pytorch-with-anaconda | <p>I installed PyTorch with:</p>
<pre><code>conda install pytorch torchvision cuda80 -c soumith
</code></pre>
<p>How do I uninstall and remove all PyTorch dependencies?</p>
| <p>From the <a href="https://conda.io/docs/commands/conda-uninstall.html" rel="noreferrer">anaconda docs</a>, you can uninstall with <code>conda uninstall</code></p>
<p>Try</p>
<pre><code>conda uninstall pytorch torchvision cuda80 -c soumith
</code></pre>
<p>Alternatively, the <a href="https://github.com/pytorch/pyt... | 532 |
pytorch | PyTorch memory model: "torch.from_numpy()" vs "torch.Tensor()" | https://stackoverflow.com/questions/48482787/pytorch-memory-model-torch-from-numpy-vs-torch-tensor | <p>I'm trying to have an in-depth understanding of how PyTorch Tensor memory model works.</p>
<pre><code># input numpy array
In [91]: arr = np.arange(10, dtype=float32).reshape(5, 2)
# input tensors in two different ways
In [92]: t1, t2 = torch.Tensor(arr), torch.from_numpy(arr)
# their types
In [93]: type(arr), typ... | <p><code>from_numpy()</code> automatically inherits input array <code>dtype</code>. On the other hand, <code>torch.Tensor</code> is an alias for <code>torch.FloatTensor</code>. </p>
<p>Therefore, if you pass <code>int64</code> array to <code>torch.Tensor</code>, output tensor is float tensor and they wouldn't share th... | 533 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.